如何在普通类的重写函数中调用Redux的dispatch方法
在非React类中调用Redux Dispatch的解决方案
你遇到的核心问题是RolloverModifierEx并非React组件,所以react-redux的connect无法生效——connect仅能为React组件注入dispatch。下面提供两种可行的解决方案:
方法一:直接导入Redux Store实例
如果你的项目中已经创建了Redux store,可以直接导出该实例,在非React类中导入后调用dispatch。
- 首先确保你的store文件导出了store实例:
// store.js import { configureStore } from '@reduxjs/toolkit'; import rootReducer from './path-to-reducers'; export const store = configureStore({ reducer: rootReducer, });
- 在
RolloverModifierEx类中导入store并调用dispatch:
import { store } from './store'; import { updateCurrentValue } from './path-to-actions'; class RolloverModifierEx extends RolloverModifier { override hitTestRenderableSeries(rs: IRenderableSeries, mousePoint: Point): HitTestInfo { const hitTest = rs.hitTestProvider.hitTestXSlice(mousePoint.x, mousePoint.y, this.hitTestRadius); // 你的业务代码... store.dispatch(updateCurrentValue({ title: dataSeriesName, currentValue: yValueCalculated })); // 其他代码... return hitTest; } }
这种方式简单直接,但缺点是会让类与store强耦合,单元测试时需要mock整个store实例。
方法二:通过依赖注入传递Dispatch
更符合React最佳实践的方式是将dispatch作为参数传入RolloverModifierEx,避免直接依赖store。
- 修改
RolloverModifierEx类,添加dispatch属性和构造函数参数:
import { updateCurrentValue } from './path-to-actions'; class RolloverModifierEx extends RolloverModifier { private dispatch; constructor(dispatch, modifierProps) { super(modifierProps); this.dispatch = dispatch; } override hitTestRenderableSeries(rs: IRenderableSeries, mousePoint: Point): HitTestInfo { const hitTest = rs.hitTestProvider.hitTestXSlice(mousePoint.x, mousePoint.y, this.hitTestRadius); // 你的业务代码... this.dispatch(updateCurrentValue({ title: dataSeriesName, currentValue: yValueCalculated })); // 其他代码... return hitTest; } }
- 在使用该类的React组件中,通过
useDispatch获取dispatch并传入实例:
import { useDispatch } from 'react-redux'; import { RolloverModifierEx } from './RolloverModifierEx'; function YourChartComponent() { const dispatch = useDispatch(); // 创建Modifier实例时传入dispatch const rolloverModifier = new RolloverModifierEx(dispatch, { hitTestRadius: 10, // 你的Modifier配置 // 其他属性 }); // 渲染图表并使用rolloverModifier return ( <div> {/* 图表组件代码 */} </div> ); }
这种方式解耦了类与store,单元测试时可以轻松传入mock的dispatch函数,更易于维护。
内容的提问来源于stack exchange,提问作者BenHero
相关产品推荐
相关产品推荐

