课堂目标
- 掌握redux
- 掌握redux中间件
- 实现redux、react-redux及其中间件原理
资源
起步
什么是Reducer
reducer:就是⼀个纯函数,接收旧的 state 和 action,返回新的 state。
(previousState, action) => newState
之所以将这样的函数称之为 reducer,是因为这种函数与被传⼊Array.prototype.reduce(reducer, ?initialValue) ⾥的回调函数属于相同的类型。保持 reducer 纯净⾮常重要。永远不要在 reducer ⾥做这些操作:
- 修改传⼊参数;
- 执⾏有副作⽤的操作,如 API 请求和路由跳转;
- 调⽤⾮纯函数,如 Date.now() 或 Math.random()
什么是Reduce
示例:
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
思考:有如下函数, 想要顺序输出1 2 3,如何处理。
function f1() {
console.log('f1')
}
function f2() {
console.log('f2')
}
function f3() {
console.log('f3')
}
⽅法1:
f1();f2();f3();
⽅法2: