【问题标题】:How to refactor redux + thunk actions/constants如何重构 redux + thunk 动作/常量
【发布时间】:2017-07-27 11:21:39
【问题描述】:

在我的 react/redux/thunk 应用程序中,我使用如下操作:

function catsRequested() {
    return {
        type: CATS_REQUESTED,
        payload: {},
    };
}

function catsReceived(landings) {
    return {
        type: CATS_RECEIVED,
        payload: landings,
    };
}

function catsFailed(error) {
    return {
        type: CATS_FAILED,
        payload: { error },
    };
}

export const fetchCats = () => ((dispatch, getState) => {
    dispatch(catsRequested());
    return catsAPI.loadCats()
        .then((cats) => {
            dispatch(catsReceived(cats));
        }, (e) => {
            dispatch(catsFailed(e.message));
        });
});

处理一些数据(简化)。一切正常,但我为每个数据实体(以及常量)都有很多代码。 我的意思是狗,老虎,鸟等的相同功能......

我看到每个实体都有类似的请求/接收/失败操作/常量。

根据 redux-thunk 缩小代码的正确方法是什么?

【问题讨论】:

标签: redux redux-thunk


【解决方案1】:

您可以通过创建类型和 thunk 创建者来保持代码 DRY:

类型:

const createTypes = (type) => ({
    request: `${type}_REQUESTED`, 
    received: `${type}_RECEIVED`, 
    failed: `${type}_FAILED`, 
});

重击:

const thunkCreator = (apiCall, callTypes) => ((dispatch, getState) => {
    dispatch({ type: callTypes.request });

    return apiCall
        .then((payload) => {
            dispatch({ type: callTypes.received, payload }));
        }, (e) => {
            dispatch({ type: callTypes.failed, payload: e.message }));
        });
});

现在你可以用 2 行代码创建一个 fetch 方法:

export const fetchCatsTypes = createTypes('CATS'); // create and export the constants
export const fetchCats = (catsAPI.loadCats, fetchCatsTypes); // create and export the thunk

export const fetchDogsTypes = createTypes('DOGS'); // create and export the constants
export const fetchDogs = (dogsAPI.loadDogs, fetchDogsTypes ); // create and export the thunk

注意:您还将在减速器中使用类型常量 (fetchDogsTypes)。

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2021-02-16
    • 2017-06-15
    • 2017-10-15
    • 2019-01-08
    • 2018-03-23
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多