盒子
盒子
文章目录
  1. Reducers

redux系统学习二

Reducers

1、处理action

reducer的格式类似(state, action) => state,很像数组中的Array.prototype.reduce(reducer, ?initialValue);中的reducer函数,并且该函数是纯函数,只充当计算功能。
一开始redux调用reducer的时候,state是undefined的,这时候正是初始化的好时机。原文:

We’ll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:

1
2
3
4
5
6
7
8
9
10
const initialValue = {
name: 'alin',
shose: [
company: 'nike'
]
}
// app reducer
function todoApp(state = initialValue, action) {
return state;
}

不用es6写法:

1
2
3
4
5
6
7
// app reducer
function todoApp(state, action) {
if (typeof state === 'undefined') {
state = initialValue;
}
return state;
}

处理改名字的action CHANGE_NAME
// app reducer
function todoApp(state = initialValue, action) {
switch(action.type) {
case ‘CHANGE_NAME’:
return Object.assign({}, state, {name, action.newName});
default:
return state;
}
}
用es6解构语法:

1
2
3
4
5
6
7
8
9
// app reducer
function todoApp(state = initialValue, action) {
switch(action.type) {
case 'CHANGE_NAME':
return {...state, name: action.newName};
default:
return state;
}
}

注意:上面的Object.assign方法属于es6语法,存在兼容性问题
处理多个action:增加 ADD_SHOSE_NAME

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// app reducer
function todoApp(state = initialValue, action) {
switch(action.type) {
case 'CHANGE_NAME':
return {...state, name: action.newName};
case 'ADD_SHOSE_NAME':
return {
...state,
shose: [...state.shose, {company: action.company}]
}
default:
return state;
}
}

拆分reducer:
拆分成name和shose两个reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// app reducer
function todoApp(state = {}, action) {
name: name(state.name, action),
shose: shose(state.shose, action)
}
// name reducer
function name(state = 'alin', action) {
switch(action.type) {
case 'CHANGE_NAME':
return action.newName;
default:
return state;
}
}
// shose reducer
function shose(state = [{company: 'nike'}], action) {
switch(action.type) {
case 'ADD_SHOSE_NAME':
return [..state, {company: action.name}];
default:
return state;
}
}

最终,redux提供了类似 上面app reducer的一个工具方法:

1
2
3
4
var todoApp = combineReducers({
name,
shose
})

和上面自己写的todoApp等价

https://redux.js.org/basics/reducers

支持一下
扫一扫,支持 Alin
  • 微信扫一扫
  • 支付宝扫一扫