我需要按顺序加载三个不同的 json 文件并进行提取(原因是我正在使用 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();
}
)
现在:我知道 setState 必须谨慎使用,因为它是异步的,但据我所知,回调函数是在状态更新后调用的,因此从这个 Angular 来看,状态应该正确更新。这种解决方案是反模式、不良做法还是出于某种原因应该避免?
代码确实有效,但我不确定这是否是实现它的方法。
最佳答案
您不需要使用 setState
回调并从状态中读取它,因为您可以直接从 res
对象中读取数据。这样你就可以制作一个扁平的 promise 链。
示例
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
});
});
关于javascript - Chain React setState 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229611/