React" TypeError:无法读取属性' state'未定义"在里面" Map"

时间:2018-03-19 09:18:37

标签: javascript reactjs state material-ui

如下所示。

时,第一张照片效果很好
this.state.blabal

不在

map(a, b){blabla}

但是像photo2一样,当我在

中移动工作精细块时
map(a, b){`here!!`}

 {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"
                    />;
                })}

它会显示错误:

  

TypeError:无法读取属性&#39; state&#39;未定义的

为什么会这样?以及如何在不单独绑定的情况下解决这个问题?

this works fine this causes the error the error message

2 个答案:

答案 0 :(得分:4)

使用箭头功能

Object.keys(newsProviderID_Name_Dic).map((key, index) => {
                return () } )

在箭头函数中,this保持与封闭范围相同的含义

答案 1 :(得分:1)

可能是您没有为Component设置初始状态。 你试试看:

class Example extends Component {
   state:{}
   render(){
   //.....code
  }
}

class Example extends Component {
    constructor(props){
      this.state={};
    }

}

祝你好运!