javascript - 我应该如何在 React 容器组件中进行 API 调用?
问题描述
目前我有一个React Redux
应用程序,其中我在商店中有大量的状态项。我设置了从后端 API 填充状态的操作。我使用容器和展示组件,在我的容器中,我使用 . 获取其子级所需的所有状态mapDispatchToProps
,然后使用mapStateToProps
.
目前,这就是我在容器组件中进行这些初始 API 调用的方式:
componentDidMount() {
this.props.getResources()
.then(() => {
this.props.getUsers()
.then(() => {
this.props.getComments()
.then(() => {
this.props.getFiles()
.then(() => {
this.props.getAlts()
.then(() => {
this.props.getSubjects()
.then(() => {
this.props.getTemplates()
.then(() => {
this.props.getResourceTags()
.then(() => {
this.setState({
resourcesLoaded: true
});
});
});
});
});
});
});
});
});
}
这看起来很荒谬。是否有更简洁的方法来发出这些 API 请求或重构我的操作,以便将它们压缩为单个操作?
解决方案
使用它同时运行所有功能/承诺的最有效方式Promise.all
componentDidMount() {
Promise.all([
this.props.getResources(),
this.props.getComments(),
this.props.getFiles(),
this.props.getAlts(),
this.props.getSubjects(),
this.props.getTemplates(),
this.props.getResourceTags()
]).then(() =>
this.setState({ resourcesLoaded: true })
)
}
使用Promise.all
over的好处await
是await
串行运行每个函数/promise,同时同时Promise.all
运行所有函数。
详细说明
所以当我们使用
await getResources()
await getComments()
...
...
关键字将await
等待getResources()
完成,然后它将运行getComments()
并等待其完成,这将继续下去。
使用Promise.all
时,它将一次运行所有函数,并等待每个函数执行完毕,然后才会运行该.then(...)
部分。
推荐阅读
- python - 在 python 3.5 中收集的 async_generator 垃圾
- php - 你知道为什么没有出现命名包消息吗?
- excel - 比较 dd/mm/yyyy 格式的两个日期
- git - 当项目包含其他子模块时 git filter-branch 不起作用
- python - 在 fasta 文件中更改反向序列的方向不起作用
- amazon-web-services - AWS 中文本处理的最佳方法是什么?
- ruby-on-rails - Ruby Rails Excel 格式数组操作
- angular - 将所有工件移至 S3 根目录
- tfs - 构建定义如何在构建过程中取消搁置给定的搁置集
- http - Postman 如何通过 HTTP 发送文件?