简体   繁体   中英

How to map over an array in JS

I'm trying to iterate over an array of Objects in React fetched from Django. My object is an array, but when I try to map it I get a typeerror: cannot read property map of undefined.

The state has structure:

Unit: { alliances: [{description: "", id: 6, name: "Elusive"}, {...}] icon_url id name }

which is what shows in React Developer tools as well. 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. 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.

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. You could also have your state as unit: {alliances: []} and skip the safe-guard altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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