Redux 简单实现(二):多文件协作

Redux 简单实现 系列文章(二):多文件协作的实现。

reducer 的拆分和合并

每一个 reducer 都只处理一个 state,如果项目里有大量的 state 需要管理,而他们每个都需要有对应的 reducer。怎么办呢?

假设我们现在需要管理 2 个数据:

1
2
3
4
5
6
7
8
9
let state = {
counter: {
count: 0
},
info: {
name: "夏目毛球",
description: "Redux 真好玩"
}
}

然后我们写好他们各自的 reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 这里的 state 到时候传进来的其实是 state.counter
function counterReducer(state, action) {
switch (action.type) {
case "INCREMENT":
return {
count: state.count + 1
}
case "DECREMENT":
return {
count: state.count - 1
}
default:
return state;
}
}

// 这里的 state 到时候传进来的其实是 state.info
function infoReducer(state, action) {
switch (action.type) {
case "SET_NAME":
return {
...state,
name: action.name
}
case "SET_DESCRIPTION":
return {
...state,
description: action.description
}
default:
return state;
}
}

现在,我们需要用一个函数来把这 2 个 reducer 合并起来。在 redux 中,负责这件事情的就是:combineReducers。示例:

1
2
3
4
const reducer = combineReducers({
counter: counterReducer,
info: infoReducer
})

combineReducers 最后会返回一个归一化的 rootReducer函数,它是最后用于被 createStore 所接收的。

我们来试着实现一下:

1
2
3
4
5
6
7
8
function combineReducers(reducers) {
return (state = {}, action) => {
return Object.keys(reducers).reduce((nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
}, {});
};
}

我们通过使用 Object.keys 获取到了 reducers 里面的每个 statePart 的 key 值。通过 reduce 方法,先用空对象进行初始化,然后遍历每一个 statePart,使用对应的 reducers[key] 来进行处理,并赋值给最终全局的 state。

相关链接

Redux 简单实现(一):状态管理器
Redux 简单实现(三):中间件
Redux 简单实现(四):react-redux

参考资料:

完全理解 redux(从零实现一个 redux)

React 状态管理与同构实战