[React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect)
As an alternate to useState, you could also use the useReducer hook that provides state and a dispatch method for triggering actions. In this lesson, we’ll centralize logic that is spread across a web application and centralize it using the useReducer hook.
NOTE: Since hooks are still a proposal and only pre-released, it’s not currently recommended to use them in production.
useReducer:
const [todos, dispatch] = useReducer((state, action) => { switch (action.type) { case "ADD_TODO": todoId.current += 1; return [ ...state, { id: todoId.current, text: action.text, completed: false } ]; case "DELETE_TODO": return state.filter(todo => todo.id !== action.id); case "TOGGLE_TODO": return state.map(todo => todo.id === action.id ? { ...todo, completed: !todo.completed } : todo ); default: return state; } },initialValue);
useReducer can accept second param as a function, so we can replace 'initialValue' with a function return a 'initialValue', which means we can using cache for the function if the param doesn't change, we always return the cache. To do that we can use
useMemo:
const [todos, dispatch] = useReducer((state, action) => { switch (action.type) { case "ADD_TODO": todoId.current += 1; return [ ...state, { id: todoId.current, text: action.text, completed: false } ]; case "DELETE_TODO": return state.filter(todo => todo.id !== action.id); case "TOGGLE_TODO": return state.map(todo => todo.id === action.id ? { ...todo, completed: !todo.completed } : todo ); default: return state; } }, useMemo(initialValue, []));
The second parameter of 'useMemo' indicates when the memorized version should change. In our case, we want it to always be the same, so passing an empty array conveys that message.
To handle side effect of action, in our case, is update localstorage, we can use useEffect:
useEffect( () => { window.localStorage.setItem("todos", JSON.stringify(todos)); }, [todos] );
---
相关文章
- Maven报错:The packaging for this project did not assign a file to the build artifact[通俗易懂]
- SqlBulkCopy – The given value of type String from the data source cannot be converted to type
- 详解React的Transition工作原理原理
- 「使用 webpack 5 从0到1搭建React+TypeScript 项目环境」2. 集成 css、less 与 sass
- 【Techo Day 腾讯技术开放日】jira React 实战
- listview嵌套GridView_react grid layout
- 美团前端二面常考react面试题及答案_2023-03-01
- react源码分析--深度理解React.Context
- React跨域配置
- 使用react+docusaurus快速搭建一个博客网站
- react源码解析16.concurrent模式
- React源码分析(三):useState,useReducer4
- React 从 v15 升级到 v16 后,为什么要重构底层架构
- React源码分析2-深入理解fiber_2023-02-20
- ORA-32342: The EXPLAIN_MVIEW facility failed to explain the materialized view statement ORACLE 报错 故障修复 远程处理
- ORA-16444: ALTER SYSTEM FLUSH REDO TO STANDBY failed due to a corrupted control file or online log file. ORACLE 报错 故障修复 远程处理
- React 许可证虽严苛,但不必过度 react
- 探索React框架中MySQL数据库的应用(react mssql)