javascript - componentDidMount 多次获取调用最佳实践?

标签 javascript reactjs api fetch

我有很多彼此独立的 api,需要在呈现之前存储在 React 状态中。我在 componentDidMount 中有 fetch 调用,但我不确定什么是解决此问题的最佳方法。 我是不是该... 1. 有嵌套的获取调用

例子:

componentDidMount() {
    fetch('url')
    .then((res) => res.json())
    .then((data) => {
        // call another fetch in here
    })

}

或 2. 有单独的获取调用

例子:

componentDidMount() {
    fetch('url')
    .then((res) => res.json())
    .then((data) => {
        // set state in here
    })

    // call another fetch for the other url endpoint
    fetch('url2')
    .then((res) => res.json())
    .then((data) => {
        // set state in here
    })
}

我不确定一种方法是否被认为比另一种方法更好,但我很想知道你们的想法以及一些优点/缺点。

更新:我现在正在使用 Promise.all(),但我得到的是返回的 Promise 而不是实际值。这是我的代码:

Promise.all([
  fetch(`/api/url1`),
  fetch(`/api/url2`),
])
.then(([res1, res2]) => (
  {
    res1: res1.json(),
    res2: res2.json(),
}))
.then(({res1, res2}) => {
  this.setState({
    state1: res1,
    state2: res2,
  });
})
.catch((error) => {
  console.log(error);
});

当我在控制台上检查我的状态值时,这是我得到的:

Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(6530)

知道我可能遗漏了什么/做错了什么吗?

谢谢!

最佳答案

至于 fetch 返回 Promise,您可以使用 Promise.all 函数并行执行两个提取:

componentDidMount() {
    Promise.all([fetch('url'), fetch('url2')])

      .then(([res1, res2]) => { 
         return Promise.all([res1.json(), res2.json()]) 
      })
      .then(([res1, res2]) => {
        // set state in here
      });
}

关于javascript - componentDidMount 多次获取调用最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882903/

相关文章:

javascript - 数组字符串在 child_process.exec 的循环中返回为未定义

javascript - php javascript - 添加删除动态表单(带有日期选择器输入)

iPhone 联系人 - 获取公司名称

java - 多维对象上的 JSONDoc 注释

php - Google API PHP 客户端 - 通讯录服务

javascript - 什么是 ...!! ES6 中的语法?

javascript - 可以禁用类型检查吗?

javascript - 我的 Provider 组件中的语法错误是什么?

node.js - Cookie session 未存储在React中

javascript - ReactJS 错误的组件被从 DOM 中删除