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;
相关推荐
前端老石人7 分钟前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html
CAE虚拟与现实7 分钟前
五一假期闲来无事,来个前段、后端的说明吧
前端·后端·vtk·three.js·前后端
Sarvartha18 分钟前
三目运算符
linux·服务器·前端
晓晨的博客25 分钟前
ROS1录制的bag包转换为ROS2格式
前端·chrome
Wect33 分钟前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·typescript
donecoding1 小时前
别再让 pnpm 跟着 nvm 跑了!独立安装终极指南
前端·node.js·前端工程化
不可能的是1 小时前
从 /simplify 指令深挖 Claude Code 多 Agent 协同机制
javascript
GISer_Jing1 小时前
AI全栈转型_TS后端学习路线
前端·人工智能·后端·学习
竹林8181 小时前
被The Graph的GraphQL查询坑了三天,我用一个真实DeFi项目把链上数据索引彻底搞懂了
前端·graphql
漫游的渔夫1 小时前
前端开发者做 Agent:别只会执行,用 4 类失败策略让 AI 知道怎么停
前端·人工智能·typescript