gpt4 book ai didi

reactjs - React-Redux : Combining reducers fails

转载 作者:行者123 更新时间:2023-12-03 13:29:37 24 4
gpt4 key购买 nike

我有一个使用 Redux 和 Redux-Thunk 构建的 React 应用程序。一切工作正常,直到我尝试根据 Redux docs 组合 reducer .

给定一个初始的功能性 reducer

export default function bigReducer(state = { events: [], flash: [] }, action) {
switch (action.type) {
case EVENTS_UPDATED:
return _.extend({}, state, { events: action.pathway_events })
case FLASH_MESSAGE_UPDATED:
return _.extend({}, state, { flash: action.flash })
default:
return state
}
}

当我尝试创建复合 reducer 时

function flashReducer(state = { flash: [] }, action) {
switch (action.type) {
case FLASH_MESSAGE_UPDATED:
return _.extend({}, state, { flash: action.flash })
default:
return state
}
}

function eventReducer(state = { events: [] }, action) {
switch (action.type) {
case EVENTS_UPDATED:
return _.extend({}, state, { events: action.pathway_events })
default:
return state
}
}

// either with simple reducer composition
export default function bigReducer(state = {}, action) {
return {
flashReducer: flashReducer(state.flash, action),
eventReducer: eventReducer(state.events, action)
}
}

// or with the combineReducers function
export default const reducer = combineReducers({
flashReducer,
eventReducer
})

初始状态和 reducer 似乎混淆了

// logging the state
var EventListContainer = connect((state) => {
console.log(state)
return { events: state.events })(React.createClass({ ...

// returns the incorrect state
# => Object {flashReducer: Array[0], eventReducer: Array[17]}

如何使用 React 和 Redux 组合 reducer ?

最佳答案

我对文档的理解是,指定的 reducer 被委托(delegate)来仅处理具有与 reducer 名称对应的顶级键的状态部分。所以

const reducer = combineReducers({
flashReducer,
eventReducer
})

意味着你有这样的状态

const state = {
flashReducer: {...},
eventReducer: {...}
}

因此,您需要a)将您的reducers命名为它们应该管理的顶级键,b)让它们的默认状态仅代表完整状态对象的子集:

function flash(state = [], action) {
switch (action.type) {
case FLASH_MESSAGE_UPDATED:
return action.flash.slice()
default:
return state
}
}

function events(state = [], action) {
switch (action.type) {
case EVENTS_UPDATED:
return action.pathway_events.slice()
default:
return state
}
}

const reducer = combineReducers({
flash,
events
})

关于reactjs - React-Redux : Combining reducers fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33636901/

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