我可以在redux操作中使用函数作为类型吗?

时间:2017-06-12 13:46:26

标签: javascript reactjs redux react-redux

我最近开始使用react + redux,我想知道在创建动作和动作创建者时如何减少样板代码。 如果我们将动作描述为不是字符串,而是将其作为函数来描述,它会返回一个动作呢? 让我解释。 通过redux指南,我们可以创建像这样的动作

const CONTRACTS_LOAD_STARTED = 'CONTRACTS_LOAD_STARTED';

实际上,我更喜欢将动作定义为地图

export const ContractsActions = {
    CONTRACTS_LOAD_STARTED: 'CONTRACTS_LOAD_STARTED',
    CONTRACTS_LOAD_OK: 'CONTRACTS_LOAD_OK',
    CONTRACTS_LOAD_ERROR: 'CONTRACTS_LOAD_ERROR'
};

然后我们写动作创作者

export function billsLoadStarted() {
    return {
        type: BillsActions.BILLS_LOAD_STARTED
    }
}

然后我们使用动作创建器来发送动作并在reducer中捕获它。

但是如果我们将动作定义为创建动作的函数呢?

export const BillsActions = {
    BILLS_LOAD_STARTED: () => {
        return {
            type: BillsActions.BILLS_LOAD_STARTED
        }
    }
};

我们可以发送它

dispatch(BillsActions.BILLS_LOAD_STARTED());

我们可以在reducer中捕获它

export function billsReducer(state, action) {

    if (typeof state === 'undefined') {
        return initState;
    }

    const response = action.response;
    switch (action.type) {
        case BillsActions.BILLS_LOAD_STARTED:
            return {
                bills: [],
                isLoading: true,
                error: []
            };
        default:
            return state;
    }
}

我们编写的代码更少。

这种定义行为的方式有什么不对?

0 个答案:

没有答案