React useReducer
Hook
useReducer Hook 與 useState Hook 類似。
它允許自定義狀態邏輯。
如果您發現需要跟蹤多個依賴於複雜邏輯的狀態,useReducer 可能會很有用。
語法
useReducer Hook 接受兩個引數。
useReducer(<reducer>, <initialState>)
reducer 函式包含您的自定義狀態邏輯,initialState 可以是簡單值,但通常會包含一個物件。
useReducer Hook 返回當前 state 和一個 dispatch 方法。
以下是一個計數器應用中 useReducer 的示例
示例
import { useReducer } from "react";
import ReactDOM from "react-dom/client";
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>
<input
type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{todo.title}
</label>
</div>
))}
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);
這只是用於跟蹤待辦事項完成狀態的邏輯。
透過新增更多操作,所有新增、刪除和完成待辦事項的邏輯都可以包含在一個 useReducer Hook 中。