-
報錯:Cannot read properties of undefined (reading 'props')
-
原因:點擊按鈕調用父組件的add方法控制台報錯,錯誤發生在子向父傳值(子組件修改父組件的值)的過程中。是this指向不正確導致。
錯誤代碼:
子組件代碼
這里發現this打印出來是undefined
解決:有兩個辦法可以修改this值
- 手動修改函數this值,調用addRecord時使用bind指定this
<button onClick={this.addRecord.bind(this)}>添加</button>
addRecord() { console.log(this); this.props.add(); }
- addRecord使用箭頭函數,讓函數的this繼承自子組件(AppForm)
<button onClick={this.addRecord}>添加</button>
addRecord = () => { console.log(this); this.props.add(); };
最后,this打印出來指向AppForm子組件。