【问题标题】:Redux: Approach to store from reducerRedux:从 reducer 存储的方法
【发布时间】:2017-09-28 04:21:40
【问题描述】:

我正在尝试从减速器中获取商店。 我看到 redux 架构不支持 reducer 之间的共享。 但在我的情况下确实需要它。

const initState = {
  schemas: [],
};


const myReducer = (state , action) => {
  state = state || initState;

  switch (action.type) {
    case 'redux-form/CHANGE':
      const schemaId = getStore().context.schema;
      let modifier = state.schemas.get(schemaId);
      modifier[action.key] = action.value;

      return {
        ...state
      };
  }
};

我的应用程序缩减器:

const iceApp = combineReducers({
  form: formReducer,
  context,
  myReducer,
});

谢谢。

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    您可以将 reducer 函数添加到任何级别的状态,请考虑:

    const complexReducer = (state, action) {
       const {context, myReducer} = state;
    
       switch (action.type) {
       case 'redux-form/CHANGE':
          // do something with myReducer
    
          return {context, myReducer};
       default:
          return state;
       }
    }
    
    // a simple utility function to call reducers in sequence on the same state
    function composeReducers(...reducers) {
        return (state, action) => reducers.reduceRight((acc, reducer) => reducer(acc, action), state);
    }
    
    const iceApp = composeReducers(complexReducer, combineReducers({
        form: formReducer,
        context,
        myReducer,
    }));
    

    这会将complexReducer 应用于来自简单reducer 的整个状态。

    另一种方法是在操作中访问context 并将其作为操作的有效负载传递。

    const changeAction = ... // the redux-form/change action
    
    const changeActionWithContext = () => (dispatch, getState) => {
       const state = getState();
       const schemaId = state.context.schema;
    
       dispatch(changeAction(schemaId));
    }
    

    我现在没有redux-form,所以我不知道是否可以将自定义有效负载添加到redux-form 操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 2018-10-02
      • 2018-09-26
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2016-04-22
      • 2016-09-27
      相关资源
      最近更新 更多