首页 > 解决方案 > 将状态值从 redux reducer 传递到另一个 reducer

问题描述

我想将redux状态的值从reducer传递给另一个reducer。就我而言,我想将groupsfrom state的值传递groupReducer.js给 to scheduleReducer.js。我正在使用combineReducersfromredux在它们之间进行组合。

这是我的代码: groupReducer.js

...
const initialState = {
groups: [],
...
export default function(state = initialState, action) {
  switch (action.type) {
  case FETCH_GROUPS:
    return {
      ...state,
      groups: action.payload
    };
...

scheduleReducer.js

const initialState = {
  ...
}
...
export default function(state = initialState, action) {
  switch (action.type) {
  case GROUP_INFO:
    return {
      group: groupInfo(action.payload.id, SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER)
    };

我想将它传递groups给最后一个减速器,我该怎么做?

标签: reactjsreduxredux-thunk

解决方案


您可以使用 thunk 访问完整的state对象。从中获取组groupReducer,然后调用您的操作SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER将这些组传递给sheduleReducer.

// thunk action creator, use it as a normal action creator     //
//  while dispatching                                            //
function passGroupFetchedFromGroupReducer() {
  return function (dispatch, getState) {

    // Get state object from getState(). Try console.log(getState() to get 
    // idea of the shape of what getState() returns.

    const groupsToPass = getState().groupReducer.groups;

    // Then dispatch your action with the payload
    dispatch({
     type: 'SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER',
     payload: groupsToPass
    })
  };
}

// scheduleReducer.js //
const initialState = {
  groups: [],
  ...
}
...
export default function(state = initialState, action) {
  switch (action.type) {
  case GROUP_INFO:
    return {
      ...state,
      groups: action.payload
  };
}

推荐阅读