gpt4 book ai didi

reactjs - 将状态值从 redux reducer 传递到另一个 reducer

转载 作者:行者123 更新时间:2023-12-04 15:53:13 31 4
gpt4 key购买 nike

我想将 redux 状态的值从 reducer 传递到另一个 reducer。在我的例子中,我想将 groups 的值从 groupReducer.js 中的状态传递到 scheduleReducer.js。我正在使用 redux 中的 combineReducers 来组合它们。

这是我的代码: 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 传递给最后一个 reducer,我该怎么做?

最佳答案

您可以使用 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
};
}

关于reactjs - 将状态值从 redux reducer 传递到另一个 reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031122/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com