Redux:从减速机存储的方法

时间:2017-04-30 14:25:41

标签: reactjs react-redux redux-thunk

我试图从减速机中取出商店。 我看到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
      };
  }
};

我的app reducer:

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

非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以将减速器功能添加到您所在州的任何级别,请考虑:

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应用于来自简单缩减器的整个状态。

另一种方法是在操作中访问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行动添加自定义有效负载。