React组件调用函数后this变undefined,无法修改state求助
React类组件中函数调用时this变为undefined的解决方案
这个问题我太熟悉了!在React类组件里,类的方法默认不会自动绑定this,所以当你把insert作为回调(比如绑定到DOM事件上)调用时,this就会丢失指向,变成undefined。下面给你三种最常用的解决办法,都能完美解决你的问题:
方法1:在构造函数中手动绑定this
这是React官方早期推荐的方式,原理是在组件初始化时就把insert的this绑定到组件实例上:
export default class Chart extends React.Component { constructor(props) { super(props); var obj=JSON.stringify(this.props.data); this.state={data: obj}; // 关键:手动绑定this到组件实例 this.insert = this.insert.bind(this); } insert(){ console.log(this); // 现在this会指向组件实例了 var json=JSON.parse(this.state.data); //... } render() { console.log(this) return( // 直接调用insert即可,比如 <button onClick={this.insert}>插入</button> ) } }
方法2:使用箭头函数定义类方法
箭头函数会自动捕获当前上下文的this,所以用箭头函数定义insert的话,就不用手动绑定了,代码更简洁:
export default class Chart extends React.Component { constructor(props) { super(props); var obj=JSON.stringify(this.props.data); this.state={data: obj}; } // 用箭头函数定义方法,自动绑定this insert = () => { console.log(this); // 这里this指向组件实例 var json=JSON.parse(this.state.data); //... } render() { console.log(this) return( // 同样直接调用 <button onClick={this.insert}>插入</button> ) } }
方法3:在调用时用箭头函数包裹
如果不想修改方法定义,也可以在render里调用的时候用箭头函数包裹,这样调用时this会指向组件实例:
export default class Chart extends React.Component { constructor(props) { super(props); var obj=JSON.stringify(this.props.data); this.state={data: obj}; } insert(){ console.log(this); // 现在this正常了 var json=JSON.parse(this.state.data); //... } render() { console.log(this) return( // 调用时用箭头函数包裹 <button onClick={() => this.insert()}>插入</button> ) } }
小提醒
第三种方法虽然简单,但每次render的时候都会创建一个新的箭头函数,如果这个组件是频繁渲染的,可能会有轻微的性能影响,所以更推荐前两种方法哦。
内容的提问来源于stack exchange,提问作者Israel Martins
相关产品推荐
相关产品推荐

