【问题标题】:Structuring the store in Redux在 Redux 中构建 store
【发布时间】:2018-03-19 11:01:35
【问题描述】:

有没有办法以这样的方式构造const reducer = (state = initialState, action),使得该方法不会被一堆开关案例臃肿?

我的想法是将相关的动作放在数组中,并在处理动作时用Array.prototype.includes()检查它们。

然后,我将提取与新方法中的特定操作相关的切换案例(例如,List 组件将具有 LIST_ADDLIST_REMOVE 等)并调用这些方法,而不是只运行 100 个案例const reducer = (state = initialState, action)方法。

这会对绩效征税,但至少是结构化的。

有更好的想法吗?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux react-redux


    【解决方案1】:

    官方 Redux docs 提供了这个非常方便的 reducer 创建器:

    function createReducer(initialState, handlers) {
      return function reducer(state = initialState, action) {
        if (handlers.hasOwnProperty(action.type)) {
          return handlers[action.type](state, action)
        } else {
          return state
        }
      }
    }
    

    它可以让你按如下方式创建你的 reducer:

    const reducer = createReducer(initialState, {
      [actionType.ACTION1]: specificActionReducer1,
      [actionType.ACTION2]: specificActionReducer2,
    }
    

    没有 switch 语句!

    【讨论】:

      【解决方案2】:

      我使用了一个名为 reduxsauce 的库,它消除了对大型 switch 语句的需求。

      https://github.com/infinitered/reduxsauce

      相反,它使用以下语法将操作绑定到方法:

      export const INITIAL_STATE = {
          values: {},
      }
      
      export const reducerFunction = (state, action) => {
          const values = action.value;
      
          return {
              ...state,
              values,
          };
      };
      
      // map the action types to the reducer functions
      export const HANDLERS = {
          [Type.ACTION_NAME]: reducerFunction,
          ...
      }
      
      // call createReducer to magically tie it all together
      export default createReducer(INITIAL_STATE, HANDLERS);
      

      【讨论】:

      • 酷,我会调查的。谢谢!
      【解决方案3】:

      您也可以尝试redux-named-reducers。允许您像这样编写减速器:

      moduleA.reduce(SOME_ACTION, action => ({ state1: action.payload }))
      moduleA.reduce(SOME_OTHER_ACTION, { state2: "constant" })
      

      它还有一个额外的好处是可以在任何地方访问 reducer 状态,例如在 mapDispatchToProps 中:

      const mapDispatchToProps = dispatch => {
        return {
          onClick: () => {
            dispatch(someAction(getState(moduleA.state1)));
          }
        };
      };
      

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2021-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 2019-05-09
        相关资源
        最近更新 更多