当前位置: 首页 > ops >正文

React hook之userReducer

在 React 中,useReducer 是一个用于管理复杂状态逻辑的 Hook,它类似于 Redux 中的 reducer 模式,但更轻量且适用于组件内部或结合 Context API 实现全局状态管理。以下是 useReducer 的详细用法指南:


1. 基本语法

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer:一个函数,接收当前状态和 action,返回新状态。
  • initialState:状态的初始值。
  • state:当前状态。
  • dispatch:用于触发状态更新的函数(发送 action)。

2. 核心概念

(1) Reducer 函数

Reducer 的格式:(state, action) => newState

  • action:通常是一个对象,包含 type(操作类型)和可选的 payload(数据)。
  • 必须返回新状态(不可直接修改原状态!)。
function reducer(state, action) {switch (action.type) {case 'INCREMENT':return { ...state, count: state.count + 1 };case 'DECREMENT':return { ...state, count: state.count - 1 };case 'SET_VALUE':return { ...state, value: action.payload };default:return state; // 默认返回原状态}
}
(2) Dispatch Action

通过 dispatch 发送 action 来更新状态:

dispatch({ type: 'INCREMENT' });
dispatch({ type: 'SET_VALUE', payload: 42 });

3. 完整示例

计数器组件
import { useReducer } from 'react';// 定义 reducer
function counterReducer(state, action) {switch (action.type) {case 'INCREMENT':return { count: state.count + 1 };case 'DECREMENT':return { count: state.count - 1 };case 'RESET':return { count: 0 };default:return state;}
}function Counter() {const [state, dispatch] = useReducer(counterReducer, { count: 0 });return (<div><p>Count: {state.count}</p><button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button><button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button><button onClick={() => dispatch({ type: 'RESET' })}>Reset</button></div>);
}

4. 进阶用法

(1) 结合 Payload 传递数据
dispatch({ type: 'SET_NAME', payload: 'Alice' });// Reducer 处理
case 'SET_NAME':return { ...state, name: action.payload };
(2) 惰性初始化

如果初始状态需要计算,可以传入一个初始化函数:

function init(initialCount) {return { count: initialCount };
}const [state, dispatch] = useReducer(reducer, initialCount, init);
(3) 结合 Context API 实现全局状态
// 创建 Context
const CounterContext = createContext();// Provider 组件
function CounterProvider({ children }) {const [state, dispatch] = useReducer(counterReducer, { count: 0 });return (<CounterContext.Provider value={{ state, dispatch }}>{children}</CounterContext.Provider>);
}// 子组件中使用
function ChildComponent() {const { state, dispatch } = useContext(CounterContext);// ...
}

5. 与 useState 的对比

场景useStateuseReducer
简单状态适合(如布尔值、数字)过度设计
复杂状态逻辑代码冗长(需多个 useState适合(逻辑集中管理)
依赖前一个状态需用函数更新(setCount(c => c + 1)自动处理(reducer 接收当前状态)
跨组件共享状态需结合 Context更适合(与 Context 天然搭配)

6. 最佳实践

  1. 拆分 Reducer
    如果逻辑复杂,可以按功能拆分成多个 reducer,再用 combineReducers(类似 Redux):

    function rootReducer(state, action) {return {counter: counterReducer(state.counter, action),user: userReducer(state.user, action),};
    }
    
  2. 避免深层嵌套状态
    尽量扁平化状态结构,便于更新。

  3. 异步操作
    dispatch 外处理异步逻辑(如 API 请求),完成后调用 dispatch

    async function fetchData(dispatch) {const data = await api.get();dispatch({ type: 'SET_DATA', payload: data });
    }
    

7. 示例:Todo 列表

function todoReducer(state, action) {switch (action.type) {case 'ADD_TODO':return [...state, { text: action.payload, completed: false }];case 'TOGGLE_TODO':return state.map((todo, index) =>index === action.payload? { ...todo, completed: !todo.completed }: todo);default:return state;}
}function TodoApp() {const [todos, dispatch] = useReducer(todoReducer, []);const [input, setInput] = useState('');const handleSubmit = (e) => {e.preventDefault();dispatch({ type: 'ADD_TODO', payload: input });setInput('');};return (<div><form onSubmit={handleSubmit}><input value={input} onChange={(e) => setInput(e.target.value)} /></form><ul>{todos.map((todo, index) => (<likey={index}onClick={() => dispatch({ type: 'TOGGLE_TODO', payload: index })}style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>{todo.text}</li>))}</ul></div>);
}

总结

  • 何时用 useReducer
    状态逻辑复杂、需要依赖前一个状态、或需要跨组件共享状态时。
  • 优势:逻辑集中、易于测试、适合与 Context 结合。
  • 注意:避免过度使用,简单场景直接用 useState 更高效。
http://www.xdnf.cn/news/12055.html

相关文章:

  • vue-19(Vuex异步操作和变更)
  • 【android bluetooth 协议分析 02】【bluetooth hal 层详解 7】【高通蓝牙hal-读流程介绍】
  • 古老界面硬核工具:小兵以太网测试仪(可肆意组包,打vlan)
  • 重启路由器ip不变怎么回事?原因分析与解决方法
  • Java八股文——集合「List篇」
  • 【计算机网络】NAT、代理服务器、内网穿透、内网打洞、局域网中交换机
  • npm install 报错:npm error: ...node_modules\deasync npm error command failed
  • linux 安装mysql8.0;支持国产麒麟,统信uos系统
  • SpringCloud——Nacos
  • SpringBoot自动化部署全攻略:CI/CD高效实践与避坑指南
  • 桂花网蓝牙网关物联网医院动态血糖管理应用案例
  • 金融系统功能测试:科技赋能,安全护航
  • 【赵渝强老师】Docker的图形化管理工具
  • 26考研 | 王道 | 计算机组成原理 | 四、指令系统
  • Sentinel微服务保护
  • 基于cornerstone3D的dicom影像浏览器 第二十八章 LabelTool文字标记,L标记,R标记及标记样式设置
  • 企业培训学习考试系统源码 ThinkPHP框架+Uniapp支持多终端适配部署
  • python训练营打卡第45天
  • python学习day39
  • Linux环境-通过命令查看zookeeper注册的服务
  • 网页前端开发(基础进阶4--axios)
  • 用 NGINX 构建高效 SMTP 代理`ngx_mail_smtp_module`
  • 软件上线前为什么要做性能测试?
  • 深度解析ArrayList
  • 05.字母异位词分组
  • AI赋能国风艺术:穿越时空的诗词画卷如何诞生?
  • Numpy——通用函数、向量化、基础的统计计算
  • Comparable和Comparator
  • React-native实战系列
  • 每日算法-250604