我有很多彼此独立的 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/