【菜鸟搭建react项目之路13】【react】Cannot read properties of undefined (reading 'props')
- 
报错: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子组件。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号