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;
相关推荐
Cocktail_py23 分钟前
JS如何调用wasm
开发语言·javascript·wasm
我有一棵树36 分钟前
深入理解html 加载、解析、渲染和 DOMContentLoaded、onload事件
前端·性能优化·html
JIngJaneIL36 分钟前
就业|高校就业|基于ssm+vue的高校就业信息系统的设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·高校就业
G***T6911 小时前
前端构建工具环境变量,安全管理
前端
Want5951 小时前
HTML礼物圣诞树
前端·html
REDcker1 小时前
Cursor Chrome DevTools MCP 配置指南 for Windows
前端·windows·chrome devtools
张可爱2 小时前
20251115复盘记录:让分页乖乖“坐好”+ 卡片统一渐变描边与圆角
前端
Jonathan Star2 小时前
基于 **Three.js** 开发的 3D 炮弹发射特效系统
javascript·数码相机·3d
Cache技术分享2 小时前
241. Java 集合 - 使用 Collections 工厂类处理集合
前端·后端
Lear2 小时前
解决Flex布局中overflow:hidden失效
前端