首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Redux thunk - Chaining调度

React Redux thunk - Chaining调度
EN

Stack Overflow用户
提问于 2018-11-02 22:18:52
回答 1查看 526关注 0票数 0

目前,我正在构建一个严重依赖API调用的应用程序。api调用是在Redux操作中使用Thunk中间件完成的,如下所示:

代码语言:javascript
复制
export const brand_fetchAll = () => {
return dispatch => {
    fetch(apiURL+'brand')
        .then(response => {return response.json();})
        .then(content => {
            dispatch({
                type: 'BRAND_STORE_ALL',
                content
            })
        })
        .catch(error => console.log(error))
}}

在我的组件中,我首先通过单独的操作获取数据。在此之后,我将打开一个编辑器:

代码语言:javascript
复制
// A component method
editModeOn(){
    // Fetch data
    this.props.dispatch(campaign_fetchAll());
    this.props.dispatch(brand_fetchAll());
    // Open editor
    this.props.dispatch(page_editModeOn());
}

现在编辑器在api调用完成之前打开,因此没有显示任何数据。可以在操作中链接分派,但我希望保持模块化,这样就不必创建数百个自定义API调用。理想情况下,我想要的是使用诸如promises之类的东西来链接它们:

代码语言:javascript
复制
    // A component method
editModeOn(){
    this.props.dispatch(campaign_fetchAll().then(brand_fetchAll()).then(page_editModeOn());
}

不幸的是,我还没有让它工作。我希望有人能帮帮我。如果您需要更多信息,我很乐意提供给您。更好的想法也非常受欢迎:)

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2018-11-02 22:23:09

回调函数是你的一个选择吗?

因此,将您的代码更新为;

代码语言:javascript
复制
export const brand_fetchAll = (callback) => {
return dispatch => {
    fetch(apiURL+'brand')
        .then(response => {return response.json();})
        .then(content => {
            dispatch({
                type: 'BRAND_STORE_ALL',
                content
            });

            callback();
        })
        .catch(error => console.log(error))
}}

// A component method
editModeOn(){
    // Fetch data
    this.props.dispatch(campaign_fetchAll());
    this.props.dispatch(brand_fetchAll(() => {
        // Open editor
        this.props.dispatch(page_editModeOn());
    }));        
}

您正在将回调链接到api调用成功的末尾,但是,您并没有紧密地耦合它是什么,因为您是根据用法传递它的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53120292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档