在React Native中将函数的返回值分配给对象属性

时间:2018-12-30 00:24:02

标签: javascript reactjs react-native object

export default class Leaderboard extends React.Component {
  
  constructor(props) {
    super(props);
    this.numLeaders = 10;
    this.topPlayers = populateLeaderboard(this.numLeaders);
    this.state = {
      tableHead: ['', 'Name', 'Age', 'School', 'Points'],
      //Trying to assign leaders array to tableTitle
      tableTitle: (function(this.numLeaders) {
        let leaders = [];
        for (let i = 0; i < numLeaders; i++) {
          leader.push(i);
        }
        return leaders;
      }())     
   
    };
  }

所以我试图在函数内生成一个数组,然后将其作为返回值分配给对象属性。我不确定是要弄乱Javascript还是React,我对Javascript对象没有很多练习。

1 个答案:

答案 0 :(得分:0)

如果您想以自己的方式来做,那就是:

this.state = {
    tableHead: ["", "Name", "Age", "School", "Points"],
    tableTitle: (() => {
      const leaders = [];
      for (let i = 0; i < this.numLeaders; i++) {
        leaders.push(i);
      }
      return leaders;
    })(),
  };
}

一个有效的例子。

const state = {
  tableTitle: (() => {
        const leaders = [];
        for (let i = 0; i < 10; i++) {
          leaders.push(i);
        }
        return leaders;
      })(),
};

console.log(state.tableTitle);

我在这里跳过了论点部分,因为您已经可以到达numleaders。为什么需要吵架?

此外,我在上方使用了箭头功能,以避免绑定this。如果您坚持使用您的版本,请不要忘记绑定它:

this.state = {
  tableHead: ["", "Name", "Age", "School", "Points"],
  tableTitle: function () {
    const leaders = [];
    for (let i = 0; i < this.numLeaders; i++) {
      leaders.push(i);
    }
    return leaders;
  }.bind(this)(),
};

或者,如果您真的想坚持使用原始原始版本:),可以尝试以下一种方法:

this.state = {
  tableTitle: (function (numLeaders) {
    const leaders = [];
    for (let i = 0; i < numLeaders; i++) {
      leaders.push(i);
    }
    return leaders;
  }(this.numLeaders)),
};

您正在传递参数,然后将其取回。此处不需要绑定this,因为您没有在函数中使用this.numLeaders

这里是一些spread syntaxkeys的选择。

this.state = {
  tableHead: ["", "Name", "Age", "School", "Points"],
  tableTitle: [...Array(this.numLeaders).keys()],
};

一个工作示例:

const state = {
  tableTitle: [...Array(10).keys()],
};

console.log(state.tableTitle);

但是,如果此数据不是动态数据,则state可能不适合使用它。