Javascript 使用for循环创建多个设置状态数据

Javascript 使用for循环创建多个设置状态数据,javascript,reactjs,Javascript,Reactjs,我一直在尝试为我的应用程序创建状态。基本上我有苹果,有身份证和身份证。所以我的代码是: constructor(props){ super(props); this.state = { apples: [], treeState: '' } } componentWillMount(){ this.setState( { apples: [ { id: '1',

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

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循环,但在网上找不到任何有用的循环。很有希望,但无法将其实现到我的代码中。我还有另一个州,我称之为“treeState”。因此,我的目标是创建一个带有ID的apple循环,并在末尾添加treeState

谢谢。

您可以使用其映射回调创建所需数量的苹果;下面是一个12的例子:

componentWillMount(){
  this.setState({
    apples: Array.from({length: 12}, (_, index) => ({id: index + 1, status: 'present'})),
    treeState: 'stagnant'
  });
}
或者,如果您愿意,为循环提供一个简单的

componentWillMount(){
  const apples = [];
  for (let id = 1; id <= 12; ++id) {
      apples.push({id, status: 'present'});
  }
  this.setState({
    apples,
    treeState: 'stagnant'
  });
}
componentWillMount(){
常量苹果=[];

对于(让id=1;我非常感谢你,Crowder先生!他们都工作得非常完美。我对JavaScript和React不熟悉,第一个有一些非常复杂但很棒的语法。