From db6f9251f2f78cefc00b476a9062a3a5862552f8 Mon Sep 17 00:00:00 2001 From: YuJian Date: Tue, 29 Mar 2022 16:49:34 +0800 Subject: [PATCH] vault backup: 2022-03-29 16:49:34 --- .obsidian/workspace | 4 +-- .../简单的 React 思考 - useReducer.md | 33 ++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) 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