1.reducer的拆分和合并
在真正的项目中,我们一定会把状态和reducer的管理,按照模块化进行划分。
第一件事情: 按照模块,把reducer进行单独管理,每个模块都有自己的reducer; 最后,我们还要把所有的reducer进行合并,合并为一个,赋值给我们创建的store! !
reducer模板
voteReducer.jsx
personalReducer.js
reducers/index.js
store/index.js中的变化
index.jsx不变
Vote.jsx中的变化
VoteMain.jsx中的变化
VoteFooter.jsx中不变
派发的操作不需要改动,每一次派发后,都会去所有reducer进行逐一匹配T用派发的行为标识,和每个模块reducer中判断的行为标识进行比较];和谁匹配成功,就执行谁的逻辑! !
2.派发行为标识宏管理
redux工程化的第二步
每一次dispalch派发的时候,都会去每个模块的reducer中找一遍,把所有和派发行为标识匹配的逻辑执行! !
可能存在的问题:团队协作开发的时候,因为开发的人多,最后很可能派发的行为标识会有冲突!!
所以我们一定要保证,不管哪个模块,哪个组件,我们派发的行为标识,必须是唯一的!!
基于"宏管理(统一管理),让所有派发的行为标识,唯性一!
store/action-types.js
voteReducer.js中定义action type的修改
personalReducer.js中定义action type的修改
VoteFooter.jsx中派发时的修改
3.actionCreator的创建
redux工程化第三步:把派发的行为对象,按照模块进行统一的管理
store/actions/voteAction.js
store/actions/personalAction.js
store/actions/index.js 合并后的action
VoteFooter.jsx中修改派发行为
从目前来看,此工程化步骤,不仅没有啥好处,反而让之前的操作更麻烦! ! !
之前每次派发,把派发的行为对象直接写出来即可!1现在,还需要把派发的行为对象,放到store/actions的某个版块下,靠方法执行们才能返回我们需要的行为对象!!
此操作的意义,我们称之为 创建actionCreator,在我们接下来,处理react-redux的时候,会非常的有用! ! !
4.combineReducers的源码
myredux-combineReducers.js
const combineReducers = function combineReducers(reducers) {
// reducers是一个对象,以键值对存储了:模块名 & 每个模块的reducer
let reducerskeys = Reflect.ownKeys(reducers);
// reducerskeys:['vote','personal']
/*
返回一个合并的reducer
+ 每一次dispatch派发,都是把这个reducer执行
+ state就是redux容器中的公共状态
+ action就是派发时候传递进来的行为对象
*/
return function reducer(state = {}, action) {
// 把reducers中的每一个小的reducer(每个模块的reducer)执行;把对应模块的状态/action行为对象传递进来;返回的值替换当前模块下的状态!!
let nextState = {};
reducerskeys.forEach(key => {
// key:'vote'/'personal'模块名
// reducer:每个模块的reducer
let reducer = reducers[key];
nextState[key] = reducer(state[key], action);
});
return nextState;
};
};
export default combineReducers;
/* store.dispatch({
type: TYPES.VOTE_SUP
}); */