ReactJS 使用Reducer Hook
useReducer Hook 是 useState 挂钩的更好替代方案,当您具有复杂的状态构建逻辑或下一个状态值取决于其先前值或需要优化组件时,通常比useState挂钩更受欢迎。
useReducer钩子接受三个参数,包括 reducer、初始状态和延迟加载初始状态的函数。
句法:
const [state, dispatch] = useReducer(reducer, initialArgs, init);
示例:这里的 reducer 是用户定义的函数,将当前状态与 dispatch 方法配对来处理状态,initialArgs 指的是初始参数,init 是用于延迟初始化状态的函数。
App.js:程序演示useReducer Hook的使用:
Javascript
import React, { useReducer } from "react";
// Defining the initial state and the reducer
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
case "reset":
return 0;
default:
throw new Error("Unexpected action");
}
};
const App = () => {
// Initialising useReducer hook
const [count, dispatch] = useReducer(reducer, initialState);
return (
{count}
);
};
export default App;
输出: