React的hooks---useReducer

useReducer 作为 useState 的代替方案,在某些场景下使用更加适合,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。

使用 useReducer 还能给那些会触发深更新的组件做性能优化,因为父组件可以向自组件传递 dispatch 而不是回调函数

复制代码
const [state, dispatch] = useReducer(reducer, initialArg, init);

使用:

复制代码
import React, { useReducer } from 'react'

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();
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

初始化 state:

useReducer 初始化 sate 的方式有两种

复制代码
// 方式1
const [state, dispatch] = useReducer(
	reducer,
  {count: initialCount}
);

// 方式2
function init(initialClunt) {
  return {count: initialClunt};
}

const [state, dispatch] = useReducer(reducer, initialCount, init);
相关推荐
网络点点滴14 小时前
Vue3路由params参数
前端·javascript·vue.js
hqk14 小时前
鸿蒙 ArkUI 从零到精通:基础语法全解析
android·前端·harmonyos
wordbaby14 小时前
React Native (Expo) iOS 真机调试失败排查:xcodebuild exited with error code 65
前端·react native
今天也很困15 小时前
解决浏览器后台定时器降频问题:用 Worker 实现高精度 setInterval
前端
只与明月听15 小时前
一次uniapp问题排查
前端·javascript·vue.js
Bacon15 小时前
Vitest 一个基于 Vite 的快速单元测试框架
前端
学不动学不明白15 小时前
AES-GCM 解密失败解决方案
前端
一水鉴天15 小时前
整体设计 定稿 之16 三层智能合约体系实现设计和开发的实时融合
前端·人工智能·架构·智能合约
小菜今天没吃饱15 小时前
DVWA-XSS(Reflected)
前端·xss·dvwa
孟祥_成都15 小时前
前端下午茶!看看炫酷的动画,轻松一下!
前端·动效