首页 > 解决方案 > 我应该如何在 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 请求或重构我的操作,以便将它们压缩为单个操作?

标签: javascriptreactjs

解决方案


使用它同时运行所有功能/承诺的最有效方式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.allover的好处awaitawait串行运行每个函数/promise,同时同时Promise.all运行所有函数。

详细说明

所以当我们使用

await getResources()
await getComments()
...
...

关键字将await等待getResources()完成,然后它将运行getComments()并等待其完成,这将继续下去。

使用Promise.all时,它将一次运行所有函数,并等待每个函数执行完毕,然后才会运行该.then(...)部分。


推荐阅读