无法运行。JavaScript/React中的数组映射

无法运行。JavaScript/React中的数组映射,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,在通过嵌套数组位置映射时出错。在此之前,这种逻辑已经起作用,我认为数组类型是相同的,因此不确定为什么在这个位置上不起作用 错误: Uncaught TypeError: this.state.locations.map is not a function 映射代码 <tbody> {this.state.locations.map(location => <tr> <td> <Link to={`${this.stat

在通过嵌套数组
位置映射时出错。在此之前,这种逻辑已经起作用,我认为数组类型是相同的,因此不确定为什么在这个
位置上不起作用

错误:

Uncaught TypeError: this.state.locations.map is not a function
映射代码

<tbody>
  {this.state.locations.map(location =>
  <tr>
    <td>
      <Link to={`${this.state.tracker.key}/locations/`}>{location.name}</Link>
    </td>
    <td>{location.canal}</td>
    <td>{location.closesttown}</td>
    <td>{location.comment}</td>
  </tr>
  )}
</tbody>
这是我可以毫无错误地映射通过的数组

0: {key: "Fr", doc: e, title: "Location", description: "My fav locations", author: "Gemma"}
1: {key: "G6", doc: e, title: "Gas", description: "Date of starting new gas cannister", author: "Gemma"}
2: {key: "za", doc: e, title: "", description: "", author: ""}
这是最初创建位置的地方:

this.state = {
      tracker: {},
      key: '',
      locations: {},
    };
onCollectionUpdate = (querySnapshot) => {
    const locations = [];
    querySnapshot.forEach((doc) => {
      const { name, canal, closesttown ,comment } = doc.data();
      locations.push({
        key: doc.id,
        doc, // DocumentSnapshot
        name,
        canal,
        closesttown,
        comment,
      });
    });
    this.setState({
      locations
   });
  }

这是我获取位置数据的地方:

this.state = {
      tracker: {},
      key: '',
      locations: {},
    };
onCollectionUpdate = (querySnapshot) => {
    const locations = [];
    querySnapshot.forEach((doc) => {
      const { name, canal, closesttown ,comment } = doc.data();
      locations.push({
        key: doc.id,
        doc, // DocumentSnapshot
        name,
        canal,
        closesttown,
        comment,
      });
    });
    this.setState({
      locations
   });
  }


第一个数组的第二个对象无效。 尝试将第二个对象的“运河”值更改为:

""""

  • 在您的状态中,有位置作为对象。如果要运行.map,它需要是一个数组
  • 地点:[]

  • 在this.state.locations中存在值之前,.map函数似乎正在尝试运行。因此,它试图在非数组/未定义/空的对象上运行.map
  • 添加一个?在.map之前,这样在定义位置且不为null之前,它不会运行.map

      {this.state.locations?.map(location => 
    
    有关?的更多信息,请参见此?。符号

  • 您可能还希望查看位置数组中的第二项。canal属性有两套报价。它只能是“而不是”

  • 位置的初始值是多少?它是一个数组吗?如何设置
    位置中的数据?@AjeetShah我已使用这些详细信息更新了位置(数组)的初始值应为空数组,因此执行
    this.state={tracker:{},键:“”,位置:[],}