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

React 项目中使用 Redux 实现公共状态共享

在 React 项目中使用 Redux 实现公共下拉选状态共享并通知各组件更新的完整方案如下:


1. 安装 Redux 必要依赖

npm install @reduxjs/toolkit react-redux

2. 创建 Redux Store 和 Slice

store/selectSlice.js
import { createSlice } from '@reduxjs/toolkit';const initialState = {value: 'default', // 默认值options: [{ value: 'opt1', label: 'Option 1' },{ value: 'opt2', label: 'Option 2' }]
};export const selectSlice = createSlice({name: 'select',initialState,reducers: {setSelectValue: (state, action) => {state.value = action.payload;},updateOptions: (state, action) => {state.options = action.payload;}}
});export const { setSelectValue, updateOptions } = selectSlice.actions;
export default selectSlice.reducer;
store/store.js
import { configureStore } from '@reduxjs/toolkit';
import selectReducer from './selectSlice';export const store = configureStore({reducer: {select: selectReducer}
});

3. 在应用顶层提供 Store

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store/store';
import App from './App';ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root')
);

4. 创建公共下拉选组件

components/GlobalSelect.js
import { Select } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { setSelectValue } from '../store/selectSlice';const GlobalSelect = () => {const dispatch = useDispatch();const { value, options } = useSelector((state) => state.select);return (<Selectvalue={value}onChange={(val) => dispatch(setSelectValue(val))}options={options}style={{ width: 200 }}/>);
};export default GlobalSelect;

5. 在任意子组件中响应状态变化

components/DisplayComponent.js
import { useEffect } from 'react';
import { useSelector } from 'react-redux';const DisplayComponent = () => {const selectValue = useSelector((state) => state.select.value);useEffect(() => {console.log('下拉选值变化:', selectValue);// 这里可以执行数据获取等副作用操作}, [selectValue]);return <div>当前选择: {selectValue}</div>;
};export default DisplayComponent;

6. 在页面中使用(完整示例)

App.js
import GlobalSelect from './components/GlobalSelect';
import DisplayComponent from './components/DisplayComponent';
import AnotherComponent from './components/AnotherComponent';function App() {return (<div style={{ padding: 20 }}><h2>公共区域下拉选</h2><GlobalSelect /><div style={{ marginTop: 50 }}><h3>组件1</h3><DisplayComponent /></div><div style={{ marginTop: 50 }}><h3>组件2</h3><AnotherComponent /></div></div>);
}export default App;

7. 异步数据加载示例(如需要)

// 在需要的地方dispatch异步action
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { updateOptions } from '../store/selectSlice';const DataLoader = () => {const dispatch = useDispatch();useEffect(() => {const fetchOptions = async () => {const res = await fetch('/api/options');const options = await res.json();dispatch(updateOptions(options));};fetchOptions();}, [dispatch]);return null;
};

关键实现原理说明:

  1. 状态集中管理:所有下拉选相关状态存储在 Redux store 中
  2. 单向数据流
    • 下拉选变更 → dispatch action → store 更新 → 所有订阅组件自动更新
  3. 组件通信
    • 任何组件都可以通过 useSelector 获取最新值
    • 任何组件都可以通过 useDispatch 修改值

性能优化建议:

  1. 精细化订阅:组件只订阅需要的具体值

    // 只订阅value变化(options变化不会触发重渲染)
    const value = useSelector((state) => state.select.value);
    
  2. 使用memo:对子组件进行记忆化

    import { memo } from 'react';
    const MemoizedComponent = memo(DisplayComponent);
    
  3. 批量更新:多个状态变更使用 redux-batched-actions


替代方案对比(Redux vs Context)

特性ReduxContext API
适用场景中大型应用小型应用
调试工具强大的Redux DevTools无内置工具
性能自动浅比较优化需要手动优化
学习曲线较高较低
异步处理内置Thunk/Saga支持需自行实现

对于需要全局共享且频繁更新的状态(如公共下拉选),Redux 仍然是更专业的选择。

http://www.dtcms.com/a/302137.html

相关文章:

  • 从 WAIC 2025 的火爆,看 AI 时代视频“入口层”的技术演进
  • flink yarn 问题排查
  • [VLDB 2025]面向Flink集群巡检的交叉对比学习异常检测
  • 数据驱动与智能重构:定制开发开源AI智能名片S2B2C商城小程序对数字营销话语权的重塑
  • Spring ai 调用大模型
  • 盲盒抽卡机小程序系统开发:连接线上线下娱乐新桥梁
  • uniapp 更新apk有缓存点不动,卸载安装apk没有问题。android
  • 小程序组件的生命周期,以及在小程序中进行接口请求的方法设置
  • 网络编程概述与UDP编程
  • 【esp32s3】7 - VSCode + PlatformIO + Arduino + 构建项目
  • 基于神经网络的手写数字识别系统
  • 【论文阅读53】-CNN-LSTM-滑坡风险随时间变化研究
  • 【论文阅读】Safety Alignment Should Be Made More Than Just a Few Tokens Deep
  • cacti的RCE
  • 计算机视觉---Halcon概览
  • 实用工具类分享:BeanCopyUtils 实现对象深浅拷贝高效处理
  • 墨者:SQL手工注入漏洞测试(MySQL数据库-字符型)
  • haproxy实列
  • 开源AI智能体-JoyAgent集成Deepseek
  • AI论文阅读方法+arixiv
  • 元宇宙工厂前端新形态:Three.js与WebGL实现3D产线交互的轻量化之路
  • 使用std::transform实现并发计算
  • Java 开发新人,入职后的环境搭建和配置
  • 安宝特方案丨AI算法能力开放平台:适用于人工装配质检、点检、实操培训
  • Netty中trySuccess和setSuccess的区别
  • python-内存管理
  • 【FAQ】MS Dynamics 365 Sales配置方法汇总
  • Linux中应用程序的安装于管理
  • Java面试宝典:Spring Boot
  • 基于BEKK-GARCH模型的参数估计、最大似然估计以及参数标准误估计的MATLAB实现