ken*_*des 5 javascript api fetch reactjs
我有很多彼此独立的 api,需要在呈现之前存储在 React 状态中。我有fetch电话,componentDidMount但我不确定解决这个问题的最佳方法是什么。我应该... 1. 嵌套 fetch 调用
例子:
componentDidMount() {
fetch('url')
.then((res) => res.json())
.then((data) => {
// call another fetch in here
})
}
Run Code Online (Sandbox Code Playgroud)
或 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
})
}
Run Code Online (Sandbox Code Playgroud)
我不确定一种方式是否被认为比另一种更好,但我很想知道你们的想法以及一些优点/缺点是什么。
更新:我现在正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)
当我在控制台上检查我的状态值时,这是我得到的:
Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(6530)
Run Code Online (Sandbox Code Playgroud)
知道我可能遗漏了什么/做错了什么吗?
谢谢!
小智 10
至于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
});
}
Run Code Online (Sandbox Code Playgroud)
正如@CertainPerformance 所提到的,您应该使用Promise.all方法。
Promise.all([
fetch("url1"),
fetch("url2"),
fetch("url3"),
]).then(([res1, res2, res3]) => {
this.setState({status: "fetched"})
})
Run Code Online (Sandbox Code Playgroud)
Promise.all([
fetch("url1"),
fetch("url2"),
fetch("url3"),
]).then(([res1, res2, res3]) => {
this.setState({status: "fetched"})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12228 次 |
| 最近记录: |