React-Redux connect结合TypeScript与withRouter使用报错求助
解决React-Redux connect + withRouter的TypeScript类型错误
嘿,我之前在TypeScript里结合React-Redux的connect和withRouter时也踩过类似的类型坑,咱们来捋清楚问题出在哪,以及怎么解决~
问题根源分析
你遇到的TS2339错误,本质是TypeScript无法识别productList属于组件接收的props类型。你的写法里有两个关键的类型隐患:
connect<{},ComponentProps,{}>:connect的三个泛型参数顺序是StateProps(从Redux映射的props)、DispatchProps(从dispatch映射的props)、OwnProps(组件自身的props),你把第一个参数设为空对象,等于告诉TS「从Redux来的props是空的」,但组件实际需要productList,类型自然冲突。withRouter<any>:用any直接跳过了路由props的类型校验,反而掩盖了类型不匹配的问题,容易引发后续错误。
分步解决方案
1. 明确定义所有props类型
先把组件需要的各类props都用TypeScript接口明确下来,避免模糊的类型推导:
// 从Redux State映射得到的props(包含productList) interface ProductListStateProps { productList: YourProductType[]; // 替换成你实际的产品类型 } // 从Redux Dispatch映射得到的props(比如异步操作方法) interface ProductListDispatchProps { fetchProductList: () => void; } // 组件自身的props + 路由props(继承RouteComponentProps获取路由相关属性) import { RouteComponentProps } from 'react-router-dom'; interface ProductListOwnProps extends RouteComponentProps { // 如果组件有自定义的传入props,在这里添加 } // 组件最终接收的props是三者的合并 type ProductListProps = ProductListStateProps & ProductListDispatchProps & ProductListOwnProps;
2. 正确编写组件和connect逻辑
组件定义时直接使用合并后的ProductListProps,确保所有需要的属性都被TypeScript识别:
import React from 'react'; const ProductListComponent: React.FC<ProductListProps> = (props) => { // 这里可以安全访问props.productList、props.fetchProductList,以及路由props(比如props.history) return ( <div> {props.productList.map(product => ( <div key={product.id}>{product.name}</div> ))} </div> ); };
然后正确配置connect的泛型参数,再结合withRouter(不需要加<any>,让TS自动推导类型):
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; // 你的mapStateToProps和mapDispatchToProps逻辑 const matchStateToProps = (state: RootState): ProductListStateProps => ({ productList: state.products.list, // 替换成你的Redux State路径 }); const matchDispatchToProps = { fetchProductList, // 替换成你的dispatch方法 }; // 先connect,再包裹withRouter,顺序别搞反 const ProductList = withRouter( connect<ProductListStateProps, ProductListDispatchProps, ProductListOwnProps>( matchStateToProps, matchDispatchToProps )(ProductListComponent) );
3. 为什么另一个组件没出错?
另一个组件的类似写法能正常工作,大概率是因为:
- 它的
ComponentProps刚好包含了connect映射的所有props类型,类型推导没有冲突; - 或者它的
mapStateToProps返回的props和组件的props类型完全匹配,即使泛型参数写得模糊,TS也能自动推导正确。
额外提示
尽量避免用any跳过类型校验,TypeScript的类型系统是用来帮你提前发现问题的,而不是阻碍开发。如果你的项目已经升级到Redux Toolkit,更推荐使用useSelector和useDispatch Hooks,它们的类型推导会更简洁直观,不需要再处理connect的泛型复杂度。
内容的提问来源于stack exchange,提问作者Prajwal
相关产品推荐
相关产品推荐

