React中点击按钮出现Cannot read property 'state' of undefined错误,求排查
解决React中Cannot read property 'state' of undefined的错误
嘿,这个问题我踩过同款坑!咱们直接看问题出在哪:
你在constructor里绑定事件函数的时候,漏传了this参数!
原本的代码里:
this.onSend = this.onSend.bind()
这里的bind()没有传入上下文对象,导致onSend函数里的this并没有绑定到当前组件实例上。当你点击按钮触发onSend时,this就变成了undefined,自然就会抛出“Cannot read property 'state' of undefined”的错误。
修正方案一:正确绑定this
把constructor里的绑定代码改成这样,顺便补全super的参数(规范写法):
constructor(props){ super(props) this.state = { email:"", guestName:"", staffName:"", }; this.onSend = this.onSend.bind(this) // 这里传入当前组件实例this }
更省心的替代方案
如果你不想手动写bind,还有两种常用方式可以避免这个问题:
方案二:使用类字段箭头函数
直接把onSend定义成箭头函数,它会自动绑定当前组件的this,不用再手动处理:
constructor(props){ super(props) this.state = { email:"", guestName:"", staffName:"", }; // 这里不需要手动bind了! } // 用箭头函数定义类方法 onSend = () => { let val = this.state console.log(val) }
方案三:在onClick中直接用箭头函数包裹
直接在点击事件里用箭头函数调用onSend,同样能保证this的指向正确:
render(){ return( <Button variant="contained" color="primary" className={"send"} onClick={() => this.onSend()} // 箭头函数包裹确保this指向组件 > Send </Button> ) }
这样改完之后,你点击按钮的时候就能正常访问到this.state啦!
内容的提问来源于stack exchange,提问作者user10398929
相关产品推荐
相关产品推荐

