【发布时间】:2019-03-23 18:53:33
【问题描述】:
我有很多相互独立的 api,需要在渲染之前存储在 React 状态中。我在componentDidMount 中有fetch 电话,但我不确定解决此问题的最佳方法是什么。
我是不是该...
1. 有嵌套的 fetch 调用
示例:
componentDidMount() {
fetch('url')
.then((res) => res.json())
.then((data) => {
// call another fetch in here
})
}
或 2. 有单独的 fetch 调用
示例:
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)
知道我可能遗漏了什么/做错了什么吗?
谢谢!
【问题讨论】:
-
如果它们不相互依赖,绝对不要嵌套它们。使用
Promise.all渲染一次 而不是两次 -
我正在使用 Promise.all(),但在我的 .then() 函数中,与承诺值(在我的例子中为对象数组)相比,我得到了返回的实际承诺。知道我可能做错了什么吗?我还用我的新代码更新了我的帖子。
标签: javascript reactjs api fetch