【问题标题】:How to get each json from Promisse.all and then atribute Json properties in setState如何从 Promise.all 中获取每个 json,然后在 setState 中属性 Json 属性
【发布时间】:2018-08-09 19:40:41
【问题描述】:

我正在使用“fetch”,一切正常。我从 API 获得了一个 json 文件,然后我将结果传递给 setState 中的对象,如下所示:

fetch(
      `https://api.io/api/v1/`, {
       method:'GET',
       headers: { 
              'content-type': 'application/json',
              'x-access-token': 'xxx-xxx-xxx',
                }
    })

  .then(res => res.json())

  .then(json => {

    this.setState({
      index: res.json.result.uv,
      isLoading: false,

      });
  });

现在我需要处理来自 API 的不同结果,在 setState 中为每个对象设置新对象。我发现“Promisse.all”能够仅在一个承诺中为我的不同请求创建一个数组。不幸的是,我没有成功尝试获取这些 json 文件。代码是这样的:

Promise.all([
fetch(
      `https://api.io/api/v1/dt=${date1}`, {
       method:'GET',
       headers: { 
              'content-type': 'application/json',
              'x-access-token': 'xxx-xxx-xxx',
                }
    }),
fetch(
      `https://api.io/api/v1/dt=${date2}`, {
       method:'GET',
       headers: { 
              'content-type': 'application/json',
              'x-access-token': 'xxx-xxx-xxx',
                }
    }),
fetch(
      `https://api.io/api/v1/dt=${date3}`, {
       method:'GET',
       headers: { 
              'content-type': 'application/json',
              'x-access-token': 'xxx-xxx-xxx',
                }
    })

  .then(res => res.json())
  .then(json => {

    this.setState({

      index: res[0].json.data,
      index1: res[1].json.data,
      index2: res[2].json.data,

      isLoading: false,
      });
  });

实际上我可以从数组中得到一个 json 文件:

.then(res => res[0].json())
  .then(json => {

    this.setState({

      index: json.data,
      isLoading: false,
      });
  });

但我在 setState 中需要多个对象(如上),所以它不适用于我的项目:

感谢大家的帮助!!!

【问题讨论】:

  • 您是否尝试将 .then(res => res.json()) 添加到您的 promise.all 数组中的每个 fetch 中?不确定这是否可行。
  • .then(responses => Promise.all(responses.map(res => res.json())))
  • @BryanEuton 我还没有尝试过,但它有效!!!!!!!谢啦!!现在我只需要让它更短哈哈

标签: javascript reactjs react-native fetch es6-promise


【解决方案1】:

可以将日期数组映射到 fetch Promise 中并使其变得更简单,并确保每个都有 then(res=>res.json()。您似乎缺少那部分

const dates = [date1, date2, date3]

const promises = dates.map(d => fetch(`https://api.io/api/v1/dt=${d}`, {
  method: 'GET',
  headers: {
    'content-type': 'application/json',
    'x-access-token': 'xxx-xxx-xxx',
  }
}).then(res => res.json()))

Promises.all(promises).then(res => {
  this.setState({

    index: res[0].json.data,
    index1: res[1].json.data,
    index2: res[2].json.data,

    isLoading: false,
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-16
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2023-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多