如果你只有一个单一的减速,你不需要combineReducers()
:
combineReducers({
user: userReducer,
messages: messagesReducer,
notifications: notificationsReducer
});
然后,你的国家可以像访问。只需直接使用它:
const initialState = {
sources: [],
left: {},
right: {}
}
function app(state = initialState, action) {
switch (action.type) {
case 'ADD_SOURCE':
return Object.assign({}, state, {
sources: [...state.sources, action.newSource]
})
case 'ADD_SOURCE_TO_LEFT':
return Object.assign({}, state, {
left: Object.assign({}, state.left, {
[action.sourceId]: true
})
})
case 'ADD_SOURCE_TO_RIGHT':
return Object.assign({}, state, {
right: Object.assign({}, state.right, {
[action.sourceId]: true
})
})
default:
return state
}
}
现在可以创建与减速商店:
import { createStore } from 'redux'
const store = createStore(app)
和部件连接到它:
const mapStateToProps = (state) => ({
sources: state.sources
})
但是你减速是难以阅读因为它一次更新许多不同的东西。现在,这是你想将它分割成几个独立的减速的时刻:
function sources(state = [], action) {
switch (action.type) {
case 'ADD_SOURCE':
return [...state.sources, action.newSource]
default:
return state
}
}
function left(state = {}, action) {
switch (action.type) {
case 'ADD_SOURCE_TO_LEFT':
return Object.assign({}, state, {
[action.sourceId]: true
})
default:
return state
}
}
function right(state = {}, action) {
switch (action.type) {
case 'ADD_SOURCE_TO_RIGHT':
return Object.assign({}, state, {
[action.sourceId]: true
})
default:
return state
}
}
function app(state = {}, action) {
return {
sources: sources(state.sources, action),
left: left(state.left, action),
right: right(state.right, action),
}
}
这是更容易维护和理解,这也使得它更容易独立地改变和测试减速。
最后,作为最后一步,我们可以使用combineReducers()
产生的根源app
减速而不是通过手工编写它的:
// function app(state = {}, action) {
// return {
// sources: sources(state.sources, action),
// left: left(state.left, action),
// right: right(state.right, action),
// }
// }
import { combineReducers } from 'redux'
const app = combineReducers({
sources,
left,
right
})
没有大的好处是用combineReducers()
,而不是通过编写根减速除了它稍微更有效率,并且可能会为您节省几个拼写错误。另外,您可以在应用程序中多次应用此模式:将无关的减速器以嵌套方式组合到单个缩减器中可以多次应用此模式。
所有这些重构对组件都没有影响。
我建议你看我的free Egghead course on Redux,它涵盖了减速机组合的这种模式,并显示了如何实现combineReducers()
。
你的代码是正确的'state.appReducer。来源'你需要减速器名 –
想象一下,你有2,3减速器每个减速器有'源'属性 –
你可以通过state.appReducer获得特定的'sources'。 sources'和'state.appReducer.2来源' –