简体   繁体   English

如何在JS中映射数组

[英]How to map over an array in JS

I'm trying to iterate over an array of Objects in React fetched from Django. 我正在尝试遍历从Django获取的React中的对象数组。 My object is an array, but when I try to map it I get a typeerror: cannot read property map of undefined. 我的对象是一个数组,但是当我尝试映射它时,我收到一个typeerror:无法读取未定义的属性映射。

The state has structure: 国家具有以下结构:

Unit: { alliances: [{description: "", id: 6, name: "Elusive"}, {...}] icon_url id name } 单位:{联盟:[{description:“”,ID:6,名称:“难以捉摸”},{...}] icon_url ID名称}

which is what shows in React Developer tools as well. 这也是React Developer工具中显示的内容。 In another component I'm doing something very similar with a state that is a nested array of units with the same structure as the above, so I'm at a loss as to why this doesn't work. 在另一个组件中,我正在使用状态非常相似的状态进行操作,该状态是具有与上述相同结构的单元嵌套数组,因此我不知道为什么它不起作用。

class UnitInfo extends Component {
  state = {
    unit: []
  };

  // ...

  render() {
    return (
      <div>
        <h1>{this.state.unit.name}</h1>
        <img src={this.state.unit.icon_url} alt="{this.state.unit.name} icon" />
        {this.state.unit.alliances.map(alliance => (
          <div key={alliance.id}>
            <h4>{alliance.name}</h4>
          </div>
        ))}
      </div>
    );
  }
}

You are fetching the data from Django, meaning that initially the data doesn't exist. 您正在从Django获取数据,这意味着最初数据不存在。 It only exists once the fetch is complete and the state has been updated. 它仅在获取完成且状态已更新后才存在。

As seen in your code example, your initial state is unit: [] , which is why you cannot map over unit.alliances because unit is an empty array and does not have an alliances property. 如您的代码示例所示,您的初始状态为unit: [] ,这就是为什么您无法映射unit.alliances原因,因为unit是一个空数组,并且没有alliances属性。

You can safe-guard against this by adding a check in your render: 您可以通过在渲染中添加检查来防止这种情况发生:

{this.state.unit.alliances && this.state.unit.alliances.map(alliance => (
  <div key={alliance.id}>
    <h4>{alliance.name}</h4>
  </div>
))}

That being said you should probably keep your state consistent and have unit be an empty object rather than an empty array. 话虽这么说,您可能应该保持状态一致,并让unit是一个空对象而不是一个空数组。 You could also have your state as unit: {alliances: []} and skip the safe-guard altogether. 您还可以将状态设为unit: {alliances: []}然后完全跳过安全防护措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM