React中在Map方法内出现TypeError: Cannot read property 'state' of undefined错误
解决React中map回调里无法访问this.state的问题
这个问题我太熟悉啦!核心原因就是你传给map的普通函数回调改变了this的指向——在普通function内部,this不再指向你的React组件实例,自然就找不到this.state了,所以才会抛出TypeError: Cannot read property 'state' of undefined这个错误。
给你三种实用的解决办法,挑你顺手的用就行:
1. 用箭头函数作为map的回调(最推荐)
箭头函数不会创建自己的this,它会直接继承外层作用域的this(也就是你的组件实例),代码改起来也最简单:
{Object.keys(newsProviderID_Name_Dic).map((key, index) => { return ( <FormControlLabel control={ <Switch checked={this.state.gilad} onChange={this.handleChange('gilad')} value="gilad" /> } label="Gilad Gray" /> ); })}
2. 手动给回调函数绑定this
通过.bind(this)把组件的this绑定到回调函数上,强制让函数内部的this指向组件实例:
{Object.keys(newsProviderID_Name_Dic).map(function(key, index){ return ( <FormControlLabel control={ <Switch checked={this.state.gilad} onChange={this.handleChange('gilad')} value="gilad" /> } label="Gilad Gray" /> ); }.bind(this))}
3. 提前保存this的引用
在render方法开头把组件的this存到一个变量(比如that或者self)里,然后在回调里用这个变量代替this:
render() { const that = this; return ( // 你的其他组件内容 {Object.keys(newsProviderID_Name_Dic).map(function(key, index){ return ( <FormControlLabel control={ <Switch checked={that.state.gilad} onChange={that.handleChange('gilad')} value="gilad" /> } label="Gilad Gray" /> ); })} // 你的其他组件内容 ); }
另外提醒一句:如果你的handleChange方法也是普通函数,记得也要给它绑定this,不然执行时可能会遇到类似的问题。比如可以在构造函数里绑定:
constructor(props) { super(props); this.state = { gilad: false }; // 绑定handleChange的this this.handleChange = this.handleChange.bind(this); }
或者直接把handleChange定义成类箭头函数:
handleChange = (name) => (event) => { this.setState({ [name]: event.target.checked }); }
内容的提问来源于stack exchange,提问作者softmarshmallow
相关产品推荐
相关产品推荐

