【问题标题】:React Redux thunk - Chaining dispatchesReact Redux thunk - 链接调度
【发布时间】:2019-04-06 19:11:37
【问题描述】:

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

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))
}}

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

// 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 调用。理想情况下,我想要的是使用承诺之类的东西来链接它们:

    // A component method
editModeOn(){
    this.props.dispatch(campaign_fetchAll().then(brand_fetchAll()).then(page_editModeOn());
}

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

提前致谢!

【问题讨论】:

    标签: async-await react-redux es6-promise fetch-api redux-thunk


    【解决方案1】:

    你可以选择回调函数吗?

    所以更新你的代码;

    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 调用成功的末尾,但是,当您根据使用情况传递它时,您并没有紧密耦合它是什么。

    【讨论】:

    • 感谢您的快速回复!这实际上非常有效!有时事情可以如此简单:) 你拯救了我的一天。
    猜你喜欢
    • 2018-10-16
    • 2018-12-19
    • 2017-08-28
    • 2018-05-21
    • 2020-08-18
    • 2018-06-25
    • 1970-01-01
    • 2019-02-02
    • 2021-04-05
    相关资源
    最近更新 更多