And*_* P. 5 javascript callback setstate chain reactjs
我需要按顺序加载三个不同的 json 文件并使用 fetch (原因是我正在使用 nextjs 导出,并且我需要动态读取这些文件,所以我在需要时获取它们,即使在出口)
第一个文件包含用于创建第二个文件的 url 的数据,依此类推,因此每次获取都需要获取实际更新的状态,
ATM 我正在使用的解决方案,因为第二个和第三个文件分别依赖于第一个和第二个文件,是获取第一个文件并使用 setState 设置一些状态,然后在 setState 回调中获取第二个文件并设置一些其他状态,很快:
fetch(baseUrl).then(
response => response.json()
).then(
res => {
this.setState({
...
}, () => {
fetch(anotherUrl+dataFromUpdatedState).then(
response => response.json()
).then(
res => {
this.setState({
...
}, () => {
fetch(anotherUrl+dataFromUpdatedState).then(
response => response.json()
).then(
res => {
this.setState({
})
}
)
})
}
).catch(
error => {
//error handling
}
)
})
}
).catch(
error => {
this.setState({ //an error occured, fallback to default
market: defaultMarket,
language: defaultLanguage,
questions: defaultQuestions
})
//this.setLanguage();
}
)
Run Code Online (Sandbox Code Playgroud)
现在:我知道 setState 必须谨慎使用,因为它是异步的,但据我所知,回调函数是在状态更新后调用的,因此从这个角度来看,状态应该正确更新。这个解决方案是反模式、不好的做法还是应该因某种原因避免?
该代码实际上有效,但我不确定这是否是执行此操作的方法。
您不需要使用setState回调并从状态中读取它,因为您可以直接从对象中读取数据res。这样你就可以建立一个扁平的承诺链。
例子
fetch(baseUrl)
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
return fetch(anotherUrl + dataFromRes);
})
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
return fetch(anotherUrl + dataFromRes);
})
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
})
.catch(error => {
this.setState({
market: defaultMarket,
language: defaultLanguage,
questions: defaultQuestions
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4923 次 |
| 最近记录: |