如何重构redux + thunk动作/常量

时间:2017-03-07 09:57:46

标签: redux redux-thunk

在我的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缩小代码的正确方法是什么?

1 个答案:

答案 0 :(得分:6)

您可以通过创建类型和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