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;
相关推荐
中微子1 分钟前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶2 分钟前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子3 分钟前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_28 分钟前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_233338 分钟前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin41 分钟前
TypeScript设计模式:适配器模式
前端·后端·node.js
遂心_1 小时前
深入理解 React Hook:useEffect 完全指南
前端·javascript·react.js
Moonbit1 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
龙在天1 小时前
ts中的函数重载
前端
卓伊凡1 小时前
非常经典的Android开发问题-mipmap图标目录和drawable图标目录的区别和适用场景实战举例-优雅草卓伊凡
前端