如何重构 redux + thunk actions/constants

How to refactor redux + thunk actions/constants

在我的 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));
        });
});

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

我看到每个实体都有相似的 requested/received/failed action/constant。

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

您可以通过创建一个类型和一个 thunk creators 来保持您的代码干燥:

类型:

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

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