diff --git a/.obsidian/workspace b/.obsidian/workspace index 2c94e06..79e1591 100644 --- a/.obsidian/workspace +++ b/.obsidian/workspace @@ -90,9 +90,9 @@ "active": "1508f46ea2481b37", "lastOpenFiles": [ "随时随地/简单的 React 思考 - useReducer.md", - "随时随地/简单的 React 思考 - Context.md", - "随时随地/简单的 React 思考 - Hook.md", "随时随地/简单的 React 思考 - Fiber 创建.md", + "随时随地/简单的 React 思考 - Hook.md", + "随时随地/简单的 React 思考 - Context.md", "基于 React Hook 开发的 Jira 系统/React 状态管理工具的简单思考.md", "随时随地/React Hooks 的碎片记录.md", "随时随地/useEffect 和 Debounce.md", diff --git a/随时随地/简单的 React 思考 - useReducer.md b/随时随地/简单的 React 思考 - useReducer.md index afed871..5a2a2e3 100644 --- a/随时随地/简单的 React 思考 - useReducer.md +++ b/随时随地/简单的 React 思考 - useReducer.md @@ -1,2 +1,33 @@ # 简单的 React 思考 - useReducer -在一些需要连续更新状态的场景下,useReducer hui \ No newline at end of file +在一些需要连续更新状态的场景下,useReducer 会比 useState 更加的合适 + +```javascript +const [state, dispatch] = useReducer(reducer, initialArg, init); +``` + +React 官网的 useReducer 实现计数器案例 +```javascript +const initialState = {count: 0}; + +function reducer(state, action) { + switch (action.type) { + 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); + return ( + <> + Count: {state.count} + + + + ); +} +``` \ No newline at end of file