理解 React 中的 useReducer 钩子
useReducer 是什么?
useReducer 是 React 16.8 中新增的 hooks 之一。它是useState
hook 的替代方案,有助于管理涉及多个子值或下一个状态依赖于前一个状态的复杂状态逻辑。与useContext
其他 hooks 结合使用时,它可以成为 redux 的良好替代方案。
此外,useReducer
由于您可以将 dispatch 向下传递而不是回调,因此它还可以优化触发深度更新的组件的性能。
如何使用 useReducer 钩子?
就像 React 中的任何其他钩子一样,您首先需要从 react 导入它。
import {useReducer} from 'react';
现在,就像钩子一样useState
,useReducer
钩子也在数组中返回两样东西:当前状态值和一个dispatch
可以传递动作并稍后调用的函数。
const [state, dispatch] = useReducer(reducer, initialState)
我们使用数组解构来获取状态并进行调度。
它useReducer
接受两个参数。第一个是 Reducer 函数,第二个是 initialState。
减速器功能:
“Reducer” 通常是一个接受两个参数并返回一个值的函数。
一个简单的例子就是我们reduce()
在 JavaScript 中传递给方法的 Reducer 函数。
let array = [1, 2, 3];
let reducer = (total, number) => {
return total + number;
}
let sum = array.reduce(reducer, 0);
console.log(sum) // 6
我们传递给的 Reducer 函数useReducer
也类似。
const initialState = { count: 0 }
// The reducer function
function countReducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 }
case 'DECREMENT':
return { count: state.count - 1 }
case 'RESET':
return {count: state.count = 0}
default:
return { count: state.count }
}
}
上面的 Reducer 函数接受两个参数,第一个是当前状态,第二个是 Action,它告诉我们要执行的操作。
这里我们使用了一个Switch
Statement,并根据 Statement 的值action.type
对状态执行相应的操作。
调度动作
现在,为了调用 Reducer 函数对状态执行操作,我们使用了该dispatch
函数。
export function Counter() {
const [state, dispatch] = useReducer(countReducer, initialState)
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'INCREMENT'})}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT'})}>-</button>
<button onClick={() => dispatch({ type: 'RESET'})}>Reset</button>
</div>
);
};
当我们调用该dispatch
函数时,当前状态会自动作为第一个参数传递。因此,我们只需传递一个 action 对象,该对象包含我们想要对当前状态执行的操作类型。
结论:
上面的示例是 useReducer 的基本实现。但是,它可以用于执行复杂的状态逻辑。在这种情况下,我们的状态和动作对象都将是许多键值对的集合。
在我的下一篇博客中,我将解释如何使用useReducer
withuseContext
进行全局状态管理。
希望您从这篇博客中学到很多东西。尝试将所学知识运用到您的项目中。如果您喜欢这篇文章,请分享,我将不胜感激。如果您有任何疑问或问题,请在下方评论。
感谢您的阅读!
文章来源:https://dev.to/amarjits/understanding-the-usereducer-hook-in-react-4k12