【问题标题】:I am getting error while fetching data in react-native在 react-native 中获取数据时出现错误
【发布时间】:2019-07-12 21:32:32
【问题描述】:

这里是api链接:

http://api.aladhan.com/v1/timingsByCity?city=Dubai&country=United%20Arab%20Emirates&method=8

<Text>{responseMsg.code}</Text>
<Text>{responseMsg.status}</Text>

上面的行是有效的。 我能够从这个 API 中获取数据,例如代码、状态,但我无法从这个 API 中获取祈祷时间。我不知道如何编写该行以从该 API 获取祈祷时间。

<Text>{(responseMsg.data || []).map(time => time.timings.Fajr)}</Text>
<Text>{(responseMsg.data || []).map(time => time.timings.Dhuhr)}</Text>

我收到以下错误TypeError: undefined is not an object (evaluating '(responseMsg.data || {}).timings.Fajr')

【问题讨论】:

  • 究竟是什么错误?
  • 错误是:TypeError: undefined is not an object (evalating '(responseMsg.data || {}).timings.Fajr')

标签: reactjs api react-native redux fetch


【解决方案1】:

您应该直接访问时间,因为 data 字段是对象而不是数组。你要写的是:

<Text>{(responseMsg.data || {}).timings.Fajr}</Text>

【讨论】:

  • 没有兄弟,它也不起作用。错误是:TypeError: undefined is not an object (evalating '(responseMsg.data || {}).timings.Fajr')
  • 哦,是的!因为在获取数据时,时间键是未定义的。也许你可以像这样{responseMsg.data &amp;&amp; responseMsg.data.timings ? &lt;Text&gt;{responseMsg.data.timings.Fajr}&lt;/Text&gt; : null} 将它包装成三元组
  • 或者您可以将其保存在变量中,例如:const {data = {}} = responseMsg; const {timings = {}} = data;
  • 它在数据>元>方法>名称.. {responseMsg.data && responseMsg.data.meta ? {responseMsg.data.meta.method.name} : null}..... 如果我这样写那么它就不行了
  • 现在可以了,兄弟。谢谢你的帮助。如果你能帮忙的话,最后一件事。我正在使用地理定位。如何在 api 链接中设置地理位置。因为 api 接受城市名称和地理位置只获取纬度和经度。
【解决方案2】:

.Map on responseMsg.data 将不起作用,因为数据是一个对象。 Map 是数组而不是对象的函数。

【讨论】:

  • 那么我如何在没有 .map 的情况下为 fetch 编写代码?
  • 不需要使用map直接用responseMsg.data.timings.Fajr访问对象即可。
猜你喜欢
  • 2019-10-05
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多