我想将redux状态的值从reducer传递给另一个reducer。就我而言,我想将groups
的值从groupReducer.js
的状态传递到scheduleReducer.js
。我正在使用combineReducers
中的redux
在它们之间进行组合。
这是我的代码:
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
传递给最后一个减速器,我该怎么做?
答案 0 :(得分:0)
您可以执行以下操作。
获取您的应用程序的运行状态创建者,然后访问组简化程序的状态以获取groups
const getGroupInfo = () => (dispatch, getState) => {
const appState = getState();
const groups = appState.groupReducerKey.groups;
// code...
dispatch({
type: ' GROUP_INFO',
payload: {
id:'',
// any other data
groups: groups,
},
});
};
// scheduleReducer.js
const initialState = {
...
}
...
export default function(state = initialState, action) {
switch (action.type) {
case GROUP_INFO:
// access here
// action.payload.groups
return {
group: groupInfo(action.payload.id, action.payload.groups)
};
}
}
我建议阅读更多有关Redux文档中的reducer之间共享数据的信息:https://redux.js.org/recipes/structuringreducers/beyondcombinereducers#sharing-data-between-slice-reducers
答案 1 :(得分:0)
您可以使用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
};
}