auto_trade_sys/frontend/REDUX_SETUP.md
薇薇安 d051be3f65 a
2026-01-22 21:30:21 +08:00

3.3 KiB
Raw Permalink Blame History

Redux 全局状态管理设置说明

📦 安装依赖

请手动运行以下命令安装 Redux 相关依赖:

cd frontend
npm install @reduxjs/toolkit react-redux

已完成的实现

1. Redux Store 结构

文件: frontend/src/store/index.js

  • 配置了 Redux store
  • 使用 @reduxjs/toolkitconfigureStore

文件: frontend/src/store/appSlice.js

  • 管理全局状态:
    • currentUser: 当前登录用户
    • viewingUserId: 管理员查看的用户ID
    • accountId: 当前选中的账号ID
    • accounts: 当前用户的账号列表
    • users: 用户列表(管理员可见)

2. 已更新的组件

App.jsx

  • 使用 Provider 包裹整个应用
  • 使用 Redux hooks (useSelector, useDispatch)
  • 用户切换逻辑使用 Redux actions

AccountSelector.jsx

  • 完全使用 Redux 管理账号选择
  • 用户切换时自动选择第一个 active 账号
  • 账号切换时自动同步到 Redux store

StatsDashboard.jsx

  • 使用 useSelector(selectAccountId) 获取当前账号ID
  • accountId 变化时自动重新加载数据

TradeList.jsx

  • 使用 useSelector(selectAccountId) 获取当前账号ID
  • accountId 变化时自动重新加载数据

Recommendations.jsx

  • 使用 useSelector(selectAccountId) 获取当前账号ID
  • accountId 变化时自动更新默认下单量

ConfigPanel.jsx

  • 使用 Redux 获取 accountId, currentUser, isAdmin
  • 移除了 localStorage 轮询和事件监听
  • accountId 变化时自动重新加载配置

GlobalConfig.jsx

  • 使用 Redux 获取 currentUser, isAdmin
  • 移除了 props 传递

🔄 工作流程

用户切换流程

  1. 管理员点击切换用户
  2. App.jsx 调用 dispatch(switchUser(userId))
  3. Redux store 更新 viewingUserId
  4. AccountSelector 监听到 viewingUserId 变化
  5. 自动加载新用户的账号列表
  6. 自动选择第一个 active 账号
  7. Redux store 更新 accountId
  8. 所有使用 useSelector(selectAccountId) 的组件自动重新渲染
  9. 各组件在 useEffect 中检测到 accountId 变化,重新加载数据

账号切换流程

  1. 用户在 AccountSelector 中选择账号
  2. AccountSelector 调用 dispatch(setAccountId(accountId))
  3. Redux store 更新 accountId
  4. 所有使用 useSelector(selectAccountId) 的组件自动重新渲染
  5. 各组件在 useEffect 中检测到 accountId 变化,重新加载数据

🎯 优势

  1. 统一状态管理: 所有用户和账号状态都在 Redux store 中
  2. 自动同步: 切换用户/账号后,所有页面自动更新
  3. 响应式: 使用 React hooks状态变化自动触发重新渲染
  4. 易于调试: Redux DevTools 可以查看所有状态变化
  5. 向后兼容: 保留了自定义事件 (ats:account:changed),确保旧代码仍能工作

📝 注意事项

  1. 需要安装依赖: 请运行 npm install @reduxjs/toolkit react-redux
  2. localStorage 同步: Redux store 会自动同步到 localStorage确保刷新后状态不丢失
  3. 事件兼容: 保留了 ats:account:changed 事件,但主要使用 Redux 状态管理

🚀 下一步

安装依赖后,系统将完全使用 Redux 管理用户和账号状态,切换用户/账号时所有页面会自动同步更新。