React useReducer Hook(钩子)
useReducer 钩子类似于 useState。
它允许自定义状态逻辑。
如果您发现自己跟踪依赖于复杂逻辑的多个状态,那么 useReducer 将会很有用。
语法
useReducer 钩子接受两个参数。
useReducer(<reducer>, <initialState>)
reducer 函数包含自定义状态逻辑,initialState 可以是一个简单的值,但通常包含一个对象。
useReducer 钩子返回当前状态 state 和 dispatch 方法。
下面是计数器应用程序中 useReducer 的一个示例:
Example:
import { useReducer } from "react";import ReactDOM from "react-dom";const initialTodos = [{id: 1,title: "Todo 1",complete: false,},{id: 2,title: "Todo 2",complete: false,},];const reducer = (state, action) => {switch (action.type) {case "COMPLETE":return state.map((todo) => {if (todo.id === action.id) {return { ...todo, complete: !todo.complete };} else {return todo;}});default:return state;}};function Todos() {const [todos, dispatch] = useReducer(reducer, initialTodos);const handleComplete = (todo) => {dispatch({ type: "COMPLETE", id: todo.id });};return (<>{todos.map((todo) => (<div key={todo.id}><label><inputtype="checkbox"checked={todo.complete}onChange={() => handleComplete(todo)}/>{todo.title}</label></div>))}</>);}ReactDOM.render(<Todos />, document.getElementById("root"));
这正是跟踪 todo 完成状态的逻辑。
通过添加更多操作,所有添加、删除和完成 todo 的逻辑都可以包含在单个 useReducer 钩子中。