在大型项目开发中,分为很多个组件模块,如果很多个action的处理都放在一个reducer里面,会导致reducer的代码非常的长,看起来也不方便,这时候需要把很长的reducer拆分,分布到各个UI组件或者模块的reducer中,然后通过总的一个reducer进行一个合并。这时候就需要用到了combineReducers。
combineReducers 辅助函数的作用是,把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数,然后就可以对这个 reducer 调用 createStore。合并后的 reducer 可以调用各个子 reducer,并把它们的结果合并成一个 state 对象。state 对象的结构由传入的多个 reducer 的 key 决定。
以todolist为例进行演示:
假设AppUI为一个大的组件,因此把他的reducer独立出来,将src/store/reducer内容复制到src/app/store/reducer中,导出名称为appUiReducer,因为这块reducer只和他自己有关,其他不关心,src/store/index内容不变。在src/store/reducer中将其他的reducer进行合并
import appUiReducer from '../app/store/reducer'
import {combineReducers} from 'redux'
const reducer = combineReducers({
app: appUiReducer
});
export default reducer
1、导入各个部分的reducer
import appUiReducer from '../app/store/reducer'
2、导入combineReducers
import {combineReducers} from 'redux'
3、导出
export default combineReducers({ app: appUiReducer });
这时候运行项目还有些问题,以为我们把合并后的appUiReducer命名为app,实际上在state中是找不到inputValue和list的,需要使用this.app.inputValue、this.app.list获取:
const mapStateToProps = (state) => { return { inputValue: state.app.inputValue, list: state.app.list } }
这时候运行项目就成功了。
但是发现import appUiReducer from '../app/store/reducer'比较长,还可以在优化,在src/app/store/reducer中创建index.js,直接导出reducer:
import reducer from "./reducer";
export {reducer}
这时候重新设置:
import {reducer as appUiReducer} from '../app/store/'
import {combineReducers} from 'redux'
const reducer = combineReducers({
app: appUiReducer
});
export default reducer
as表示请求命名reducer为appUiReducer防止重名。