本文目标:但愿经过买水果生鲜的例子,和你们探讨一下如何用
redux
处理比较复杂的store
模型。node
在上一篇文章 Redux 入门 -- 基础用法中,阿大用 redux
开起了水果店。git
谁知道水果店生意愈来愈好,因而阿大开始拓展业务,不只卖水果,还卖起了生鲜,因而有了水果部和生鲜部。github
因而阿大想了想将来购买生鲜的顾客的行为:redux
// 买生鲜 - 鸡蛋
function buyEgg(num) {
return {
type: 'BUY_EGG',
payload: {
count: num
}
}
}
复制代码
分了不一样的部门以后,不一样的业务有不一样的记帐方式,得分帐记了,开来要增长一个生鲜的记帐本:app
const freshState = {
egg: 0
};
复制代码
原来的水果帐本也要改个名字:async
- const state = {
+ const fruitsState = {
apple: 0
};
复制代码
而后增长生鲜部的收银员, 管理生鲜帐本 freshState
:post
// 生鲜部收银员
function freshReducer(state = freshState, action) {
if (action.type === 'BUY_EGG') {
return Object.assign({}, state, {
egg: state.egg + action.payload.count
});
}
return state;
}
复制代码
而后原来水果部的收银员管理水果帐本 fruitsState
须要修改下:ui
// 水果部收银员
- function reducer(state, action) {
+ function fruitReducer(state = fruitState, action) {
if (action.type === 'BUY_APPLE') {
return Object.assign({}, state, {
apple: state.apple + action.payload.count
});
}
return state;
}
复制代码
可是阿大并不想看各个部门的分帐本,他只想看一个总帐本就行了。恰好 redux
提供了 combineReducers
功能,能够把各个收银员管理的帐本合起来:spa
- const { createStore } = require('redux');
+ const { createStore, combineReducers } = require('redux');
// 总帐本
+ const state = {
+ fruits: fruitsReducer,
+ fresh: freshReducer
+ };
// 总收银员
+ const reducer = combineReducers(state);
// 建立新的水果生鲜店
- const store = createStore(reducer, state);
+ const store = createStore(reducer);
复制代码
这样,水果生鲜店就能够营业了,销售员又开始处理顾客的购物需求了:code
store.dispatch(buyApple(3)); // {"fruit":{"apple":3},"fresh":{"egg":0}}
store.dispatch(buyEgg(1)); // {"fruit":{"apple":3},"fresh":{"egg":1}}
store.dispatch(buyApple(4)); // {"fruit":{"apple":7},"fresh":{"egg":1}}
store.dispatch(buyEgg(8)); // {"fruit":{"apple":7},"fresh":{"egg":9}}
// ...
复制代码
升级以后的水果生鲜店又稳妥当当的运营起来了,阿大内心美滋滋~
当业务场景愈来愈复杂的时候,state 的结构也会变得愈来愈复杂并且庞大。若是只用一个 reducer 来计算 state 的变化势必会特别麻烦。这个时候咱们就能够把 state 里独立的数据分离出来,单独用一个 reducer 来计算,而后再经过 combineReducers
方法合入到 state 中。
combineReducers 接收一个对象,这个对象就是最终的 state
const reducer = combineReducers({
fruits: fruitsReducer,
fresh: freshReducer
});
复制代码
代码地址:Redux 入门 -- 拆分 reducer,直接控制台运行
node ./demo2/index.js
查看效果
上一篇:Redux 入门 -- 基础用法