相信很多人对于变成中reduce、reducer命名都存在困惑,为了更好理解useRedecuer,我们不妨先来说说reduce。
如何理解reduce和reducer
reduce:函数式编程当中的一个术语,reduce操作被称为Fold折叠
// 通过reduce,数组实现折叠。reduce函数的的入参数被称为reducer
const sum = [0, 1, 2].reduce((prev, item) => {
return prev + item;
}, 0)
拿JavaScript来理解。reduce属于一种高阶函数,它将其中的回调函数reducer递归应用到数组的所有元素上并返回一个独立的值。这也就是“缩减”或“折叠”的意义所在了。
reducer:(state, action) => newState
redux中的reducer函数是因为它的入参和返回值都非常类似于arr的reduce中传入的回调函数
// reducer接收两个参数: state=[], action
// reducer返回值是一个新的state
const todos = (state=[], action) => {
switch(action){
case "ADD":
return [...state, {id: 111}];
default:
return state;
}
}
useReducer是啥,和useState有什么关系区别
useRedcuer是useState的替换方案
和useState相比,它更适合state逻辑复杂,或者state是个对象,包含多个子值,或者下一个state依赖于之前的stated的情况。相当于收敛逻辑于reducer函数中进行管理
useReducer使用
用useReducer实现一个
const reducer = (state, action) => {
switch (action) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};
function Reducer() {
const [num, dispatch] = useReducer(reducer, 1);
return (
<div>
<p>
useStateByReducer :
<button
onClick={() => {
dispatch('DECREMENT');
}}
>
-
</button>
{num}
<button
onClick={() => {
dispatch('INCREMENT');
}}
>
+
</button>
</p>
</div>
);
}
export default Reducer;
用useReducer实现一个useState
import { useReducer, useRef } from 'react';
const isFunction = (fn) => {
return Object.prototype.toString.call(fn) === '[object Function]';
};
export default (initialState) => {
const reducer = (state, action) => {
return isFunction(action) ? action(state) : action;
};
return useReducer(reducer, initialState);
};