前言:
之前我们在写react组件时,我们要么是通过类组件内定义state来管理数据,要么就是在函数组件内使用useState来管理数据。但如果一个数据牵扯到了很多个组件,那么我们管理起来就会十分麻烦。
所以 react-hooks 为我们提供了一个类似与redux的功能 – useReducer来帮助我们集中式的处理复杂的state管理。
一、useReducer的使用
useReducer接收三个参数(第三个可不传):
第一个参数:reducer函数。
第二个参数:初始化的state。返回值为最新的state和dispatch函数(用来触发reducer函数,计算对应的state)。按照官方的说法:对于复杂的state操作逻辑,嵌套的state的对象,推荐使用useReducer。
第三个参数(一个函数,用于惰性初始化):你可以选择惰性地创建初始 state。为此,需要将 init 函数(接收initialState,可对其进行一些处理)作为 useReducer 的第三个参数传入,这样初始 state 将被设置为 initialArg。
const [state, dispatch] = useReducer(reducer, initialState, init);
用useReducer实现一个计数器:
const initialState = {
count: 0}; // 设置初始状态
// reducer:负责生成新的State
function reducer(state, action) {
// 定义 reducer 函数,在这里面对状态改变 进行统一处理,
// state:是上一次state的状态数据
// action:是基于dispatch派发的行为数据:值 或 一个对象
switch (action.type) {
// 根据action 对 State 进行修改
case 'increment':
return {
count: state.count + 1};
case 'decrement':
return {
count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
// dispatch 派发action
return (
<>
Count: {
state.count}
<button onClick={
() => dispatch({
type: 'decrement'})}>-</button>
<button onClick={
() => dispatch({
type: 'increment'})}>+</button>
</>
);
}
使用useState实现计数器:
function App() {
const [state, setState] = useState({
count: 0
});
const increment