You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript编写的React类组件中获取Redux Store及调用Dispatch

在React类组件中使用Redux Store与Dispatch

核心实现:借助connect高阶组件

类组件无法直接使用React-Redux的Hook(如useDispatch/useSelector),需通过connect高阶组件将Redux的状态和dispatch能力映射到组件props中,这是类组件对接Redux的标准方式。

改写后的类组件代码

结合你提供的Redux配置,原函数式组件可改写为如下类组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { RootState } from './../store/store';
import { setRelease } from './../store/factorySlice/factorySlice';

// 定义组件接收的Props类型
type XProps = {
  selectedRelease: string; // 根据实际业务类型调整
  setRelease: () => void;
};

class X extends Component<XProps> {
  render() {
    const { selectedRelease, setRelease } = this.props;
    return (
      <>
        {selectedRelease}
        <button onClick={setRelease}>Click</button>
      </>
    );
  }
}

// 映射Redux状态到组件props
const mapStateToProps = (state: RootState) => ({
  selectedRelease: state.factory.selectedRelease,
});

// 映射dispatch到组件props
const mapDispatchToProps = {
  setRelease, // 直接传入action creator,connect会自动绑定dispatch
};

// 用connect包装组件,完成状态与dispatch的注入
export default connect(mapStateToProps, mapDispatchToProps)(X);

关键细节说明

  • mapStateToProps:接收整个Redux Store的状态,返回需要注入到组件的状态片段,确保组件只获取自身需要的数据。
  • mapDispatchToProps:以对象形式传入action creator时,connect会自动将其包装为可直接调用的函数(内部已绑定dispatch),无需手动调用dispatch(setRelease())。
  • 类型安全:通过XProps和RootState的类型定义,保证TS环境下的类型校验。

备选方案:直接访问Store实例(不推荐)

若需在生命周期方法等场景直接操作Store,可直接导入Store实例,但这种方式会让组件与Store强耦合,不利于维护和复用:

import store from './../store/store';

// 在组件内部使用
store.dispatch(setRelease());
const currentRelease = store.getState().factory.selectedRelease;

内容的提问来源于stack exchange,提问作者Eldar Tailov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 00:46:03