Redux是编写reducer的更好方法?

And*_*cik 5 typescript reactjs redux react-redux

我认为Redux具有很大的价值,但是对我来说,主要问题在于当今的reducer的编写方式:

const addToDoReducer = (state, action) => {
    switch (action.type) {
        case ADD_TODO:
            return Object.assign({}, state, {
                todos: todos(state.todos, action)
            })
        case TOGGLE_TODO:
            return Object.assign({}, state, {
                todos: todos(state.todos, action)
            })
        default:
            return state
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 简化器太通用了(您可以写出this肿的简化器来处理各种不同的动作并容易造成混乱),如果这没有违反单一职责原则
  • switch语句施加维护方面的影响,例如对一种情况的更改可能会破坏其他情况(例如,已经有效的代码)
  • 始终重复“默认:返回状态”(失败DRY)
  • 所有的reducer总是被调用(调用函数什么都不做只是错误的)

...最终,减速器成为项目的薄弱环节

问:有没有更好的方法/选项来编写reducer:

  • 仅针对特定操作调用(基于操作对象的类型)
  • 消除了switch语句

像这样:

const addToDoReducer = (state:toDoState, action:addAction) =>
{
    return { ...state, toDos: [...state.toDos, action.toDoObject] };
}
Run Code Online (Sandbox Code Playgroud)

还是已经有这样做的图书馆?

Nik*_*Nik 0

您可以创建这样的模块:

// createReducer.js
export default (initiateState, reducerMap) => {
    return function(state, action) {
        const currentState = state !== undefined ? state : initiateState;
        const handler = reducerMap[action.type];
        return handler ? handler(currentState, action) : currentState;
    };
};
Run Code Online (Sandbox Code Playgroud)

然后,在第一个参数中设置初始状态并将操作列表存储为对象。例如:

import createReducer from './createReducer';

const STORE_TEST_MODULE = 'STORE_TEST_MODULE';

export default createReducer(
    // Initial state
    {
        test: null,
    },   
    {
        // Custom action #1
        [STORE_TEST_MODULE]: (state, action) => {
            return {...state, ...action.payload};
        },

        // Custom action #2
        'CLEAR_TEST': (state, action) => {
            return {test: null};
        },
    }
);
Run Code Online (Sandbox Code Playgroud)