2 回答
TA貢獻1858條經驗 獲得超8個贊
componentDidMount您正在構造函數中調用生命周期方法,您不應該那樣做。
這是問題所在:
this.componentDidMount = this.componentDidMount(this);
如果您在 中執行此操作constructor,您會收到該警告,React 會告訴您該組件尚未安裝,但您已經setState通過手動調用componentDidMount.
在您的情況下,構造函數尚未完成執行,并且組件沒有機會安裝到 DOM 上。一旦構造函數被執行,組件就被初始化,然后組件被實際掛載到 DOM 上。
安裝組件后,你的生命周期方法componentDidMount將由 React 以適當的上下文調用(因此不需要調用bindon componentDidMount),然后在那個時間點你應該調用setState來改變組件的狀態。
您也可以刪除_isMounted與該財產形式相關的 和檢查componentDidMount,componentWillUnmount因為它不是必需的。
TA貢獻1827條經驗 獲得超8個贊
componentDidMount 是一種生命周期方法,不需要在構造函數中進行初始化。刪除它以避免警告。
constructor(props){
super(props);
this.state = {list:[], itemCounter: 0};
this.addItem = this.addItem.bind(this);
this.handleDone = this.handleDone.bind(this);
this.componentDidMount = this.componentDidMount(this); // remove this, componentDidMount is a lifecycle method.
}
添加回答
舉報
