处理“立即调用”函数作为对象属性

时间:2016-01-14 19:23:47

标签: javascript function object reactjs state

在我做的一个小型React项目中,我想通过调用函数来初始化getInitialState中的数组。参数引用getInitialState中的另外两个属性。我就这样做了:

  getInitialState() {
    return {
      numRows: 55,
      numCols: 47,
      arrInit: function(){
        this.grandArr = this.initBlank(this.numRows, this.numCols);
        return this;
      },
    }.arrInit(); //Creates `grandArr` in the `state`
  }

this.initBlank是组件中返回数组的方法。)

链接arrInit的方式看起来非常混乱。有更好/更清洁的方法吗?

1 个答案:

答案 0 :(得分:3)

看起来您期望this引用state对象和组件。我会进行设置,然后返回你想要的对象:

getInitialState() {
  const numRows = 55,
        numCols = 47,
        grandArr = this.initBlank(numRows, numCols);

  return {numRows, numCols, grandArr};
}
相关问题