React TS中withRouter与connect组合使用报错求助
解决React TypeScript中withRouter与connect结合的类型错误
我之前也碰到过这个类型不兼容的问题,本质是TypeScript没法自动推断connect包装后的组件和withRouter所需RouteComponentProps之间的类型匹配——connect默认会剥离组件的原始props类型,导致withRouter认为你的组件不接受路由相关的props,从而抛出类型错误。下面给你几个实用的解决办法:
方法1:显式指定connect的泛型参数
最稳妥的方式是给connect明确指定泛型参数,让TypeScript清楚组件的props结构。步骤如下:
- 先定义
MainPage的props类型,让它继承RouteComponentProps(包含路由所需的history、location、match):
import { RouteComponentProps } from 'react-router-dom'; import { connect } from 'react-redux'; // 替换成你的Redux根状态类型 type RootState = { someReducer: { someValue: string; }; }; // 定义MainPage的props:路由props + Redux映射的props type MainPageProps = RouteComponentProps & { someStateProp: string; }; class MainPage extends React.Component<MainPageProps> { // 你的组件逻辑 render() { // 可以直接使用this.props.history等路由props return <div>{this.props.someStateProp}</div>; } }
- 在
connect时显式传入泛型参数,顺序是StateProps, DispatchProps, OwnProps, RootState(没有dispatch props就用{}占位):
const mapStateToProps = (state: RootState) => ({ someStateProp: state.someReducer.someValue }); // 显式指定泛型,确保connect返回的组件类型包含RouteComponentProps export default withRouter(connect<MainPageProps, {}, {}, RootState>(mapStateToProps)(MainPage));
方法2:用类型断言引导TypeScript推断
如果不想写太多泛型参数,也可以用类型断言告诉TypeScriptMainPage的props类型,让connect正确识别:
// 同样先定义包含RouteComponentProps的MainPageProps type MainPageProps = RouteComponentProps & { someStateProp: string; }; // 用类型断言指定MainPage的组件类型 const ConnectedMainPage = connect(mapStateToProps)(MainPage as React.ComponentType<MainPageProps>); // 此时withRouter就能正确识别组件接受RouteComponentProps export default withRouter(ConnectedMainPage);
方法3:升级依赖(针对旧版本类型bug)
如果你的@types/react-router-dom或@types/react-redux版本比较旧,可能存在类型定义的bug,升级到最新稳定版就能解决:
npm install @types/react-router-dom@latest @types/react-redux@latest --save-dev
内容的提问来源于stack exchange,提问作者shoopik
相关产品推荐
相关产品推荐

