【问题标题】:React Native: Cannot map over state array [duplicate]React Native:无法映射状态数组[重复]
【发布时间】:2018-04-09 17:24:00
【问题描述】:

我试图弄清楚如何通过 api 调用映射存储在我的状态中的对象数组。

我的状态对象

state = {
    isLoading: false,
    event: []
};

我的渲染函数

{this.state.event.musicStyle.map((style, index) => {
    return <Text>{style}</Text>;
})}

我的 API 响应

this.state.event 的控制台日志

错误信息

TypeError: Cannot read property of 'map' of undefined

我在这里做错了什么?非常感谢任何帮助。

【问题讨论】:

  • 我认为这个问题是因为它第一次渲染时,this.state.event 的值仍然是空的(不完全是空的,因为你一开始设置为一个空数组)所以访问 this.state.event.musicStyle 将给出一个错误。我认为您需要更改以将event初始化为null,然后检查event是否为not null,然后您可以执行map
  • 这部分正确,但主要问题是this.state.event 是一个数组,因此this.state.event.musicStyle 将始终未定义。在javascript中访问数组索引的方式是&lt;array&gt;[position in array]

标签: reactjs react-native


【解决方案1】:

this.state.event 是一个数组,因此this.state.event.musicStyle 将始终未定义...

你想要的是类似的东西

componentDidMount() {
  return fetch(callToApi)
    .then(result => result.json())
    .then(result => this.setState({event: result})
}
render() {
  return (
    {this.state.event.map((event) => {
      event.musicStyle.map((style) => {
       return <Text>{style}</Text>;
      })  
    })}
  )
}

【讨论】:

  • 感谢麦克斯韦的回复。我在 componentDidMount 函数中调用 this.setState,数据成功存储在我的状态中。知道如何映射事件数组的子数组吗?
  • @Menelik 请检查我编辑的回复。您只需要为每个事件遍历 musicStyle 数组:)
  • 再次感谢 Maxwelll 尝试帮助我,非常感谢。当我使用您的代码时,我收到一条新的错误消息:TypeError:this.state.event is not a function ;( 我这边是否存在一般设计错误?因为这是一个事件详细信息页面,可能不需要将 state.event 声明为数组?会有仅在此屏幕上提供有关一个事件的详细信息。
  • 对不起,我忘了.map :D
  • 我终于用 Shubham Khatri 的链接问题解决了它。我必须提供未定义的检查。以下代码现在正在运行{this.state.event.musicStyle &amp;&amp; this.state.event.musicStyle.map(style =&gt; { return &lt;Text&gt;style&lt;/Text&gt;; })}
猜你喜欢
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2019-12-03
  • 2020-05-14
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多