【问题标题】:Fetch multiple urls then set state accordingly React Native获取多个 url,然后相应地设置状态 React Native
【发布时间】:2020-11-09 19:12:14
【问题描述】:

我正在尝试获取多个 .png 图像,然后相应地设置我的状态。 我已经设法在不使用 Promise.all 的情况下异步获取所有 url;然而,随后的 setstate 函数在 promise 解决之前被执行。因此,我将代码更改为包含promise.all,但似乎我没有正确使用该函数。我收到错误“未定义不是函数(靠近'...podexData.map...')”。有谁知道怎么回事?

【问题讨论】:

  • 请在帖子中提供相关代码,作为代码而不是图像。

标签: javascript react-native async-await promise.all


【解决方案1】:

执行以下操作

const reqArray = [];
podexData.map(pokemon => reqArray.push(fetch(pokemon.url)));

Promise.all(reqArray).then(allResponses => {
  allResponses.map(pokemonData => 
    dex.push(....);
  );
  this.setState({...});
  ...

})

【讨论】:

  • 非常感谢您的帮助!!!我想我需要以某种方式将响应转换为 json。通常我会在 fetch 调用之后调用 .then(resp=>resp.json()) ,但我不知道该怎么做。你有什么想法吗?
  • 我添加了行 .then(responses => Promise.all(responses.map(r => r.json()))) 并且效果很好!!谢谢你:)
猜你喜欢
  • 2022-01-17
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多