使用for循环创建多个setState数据

时间:2018-10-17 17:36:08

标签: javascript reactjs

我一直在尝试为我的应用程序创建状态。基本上我有具有ID和状态的苹果。所以我的代码是:

constructor(props){
    super(props);
    this.state = {
      apples: [],
      treeState: ''
    }
  }

  componentWillMount(){
    this.setState(
      {
        apples: [
      {
        id: '1',
        status: 'present'
      },
      {
        id: '2',
        status: 'present'
      },
      {
        id: '3',
        status: 'present'
      }
    ],
  treeState: 'stagnant'});
  }

到某个时候,我将有十到十二个苹果。手动创建它们既耗时又效率低下。我需要一个for循环,但找不到任何有用的在线循环。 This one很有希望,但无法将其实现到我的代码中。另外,我还有一个称为“ treeState”的状态。因此,创建具有ID的苹果循环并在最后添加treeState是我的目标。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用Array.from及其映射回调来创建所需数量的苹果;这是一个带有12的示例:

componentWillMount(){
  this.setState({
    apples: Array.from({length: 12}, (_, index) => ({id: index + 1, status: 'present'})),
    treeState: 'stagnant'
  });
}

或者,如果愿意,可以使用一个简单的for循环:

componentWillMount(){
  const apples = [];
  for (let id = 1; id <= 12; ++id) {
      apples.push({id, status: 'present'});
  }
  this.setState({
    apples,
    treeState: 'stagnant'
  });
}
相关问题