无法在Object.keys中读取未定义的属性'setState',做出反应

时间:2017-12-27 00:39:52

标签: javascript reactjs

我正在使用:method = () => { }所以我不需要绑定函数

这是我的班级:

class Form extends Component {

  constructor(props) {
    super(props);

    this.state = {
      disabledFields: [],
    };

  }

  executeCode = ( methodCode ='', params = {} ) => {
    const result = crudCode[methodCode](params);
    if (result && result.newStates) {

      Object.keys(result.newStates).map(function(keyName, keyIndex) {
          this.setState( {  nada: 'nada' });
        });
    }
  }

我收到此错误:

TypeError: Cannot read property 'setState' of undefined
> 48 |         this.setState( {  nada: 'nada' });

我做错了,我已经使用过这种类型的函数和setState,但我不知道这次它不起作用。

1 个答案:

答案 0 :(得分:4)

您在var listOfLists = new List<List<string>>(); // Setup test data for (int i = 0; i < 10; i++) { listOfLists.Add(Enumerable.Range(0, 10000).Select(z => z.ToString()).ToList()); } // Pre-allocate Capacity here - this will have the most benefit for listOfLists consisting of a small number of large lists var capacity = 0; for (int i = 0; i < listOfLists.Count; i++) capacity += listOfLists[i].Count; List<string> result = new List<string>(capacity); for (int i = 0; i < listOfLists.Count; i++) // changed to for loop based on Tommaso's advice { result.AddRange(listOfLists[i]); // AddRange is faster than Add - https://stackoverflow.com/a/9836512/34092 } 回调中不使用箭头功能:

map

因此,它不受Object.keys(result.newStates).map(function(keyName, keyIndex) { this.setState( { nada: 'nada' }); }); 的约束。

这将改为:

this