react: useReducer

相比useState, 用来处理更为复杂的修改数据方式

javascript 复制代码
// 使用示例
import  { useReducer } from "react";
const reducer函数 = (state, action) => {
 根据action做判断 去返回结果
 return state
}
const [state, dispatch函数] = useReducer(reducer函数, action)

使用
dispatch(传递不同的action)

https://ant.design/components/button-cn 打开一个codesanbox替换下面代码保存即可

javascript 复制代码
import React, { useReducer } from "react";

// 定义 reducer。它接收当前状态和一个代表"动作"的对象,返回新状态。
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, { count: 0 });

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

export default Counter;
相关推荐
我命由我1234516 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_17 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝17 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_18 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户9385156350718 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
圣殿骑士-Khtangc19 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne20 小时前
【ijkplayer】 硬解码流程
前端
kyriewen20 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek
捡田螺的小男孩21 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员
IT_陈寒21 小时前
Redis集群这个坑,差点让我通宵
前端·人工智能·后端