React类组件中this.props无法获取参数,编译报错求助
解决React类组件(TSX)获取路由参数的TypeScript类型错误
我之前也碰到过一模一样的TypeScript报错,这个TS2339错误的核心原因是:TypeScript没办法自动识别你组件props里match.params或者解析后的查询参数包含firstName这个属性,必须手动给组件的Props定义明确的类型,才能让TS正确推断这些属性的存在。
下面分两种常见场景给你具体的解决方案:
场景1:获取URL路径参数(比如/sample/:firstName)
如果你的firstName是通过路由路径参数传递的,按照以下步骤处理:
先确保安装了React Router的TypeScript类型定义包:
npm install @types/react-router-dom --save-dev在组件中导入
RouteComponentProps,并自定义路径参数的类型:import React, { Component } from 'react'; import { RouteComponentProps } from 'react-router-dom'; // 定义路径参数的类型,明确firstName是字符串类型 interface SampleRouteParams { firstName: string; } // 让组件的Props类型继承RouteComponentProps,泛型传入我们定义的参数类型 interface SampleComponentProps extends RouteComponentProps<SampleRouteParams> { // 如果你还有其他自定义props,可以在这里添加 } class Sample01 extends Component<SampleComponentProps> { render() { // 现在TS能正确识别match.params里的firstName,不会再报错 const { firstName } = this.props.match.params; return <div>Hello, {firstName}!</div>; } } export default Sample01;
场景2:获取URL查询参数(比如/sample?firstName=John)
如果firstName是通过URL查询字符串传递的,需要给解析后的查询结果指定类型:
import React, { Component } from 'react'; import { RouteComponentProps } from 'react-router-dom'; import queryString from 'query-string'; // 定义查询参数的类型,这里把firstName设为可选(因为查询参数可能不存在) interface SampleQueryParams { firstName?: string; } // 组件Props继承RouteComponentProps即可 interface SampleComponentProps extends RouteComponentProps { // 自定义props在这里添加 } class Sample01 extends Component<SampleComponentProps> { render() { // 解析查询参数时,用类型断言告诉TS这是我们定义的SampleQueryParams类型 const queryParams = queryString.parse(this.props.location.search) as SampleQueryParams; // 给个默认值避免undefined的情况 const firstName = queryParams.firstName || 'Guest'; return <div>Hello, {firstName}!</div>; } } export default Sample01;
额外提醒
- 如果你使用的是React Router v6,类组件需要通过
withRouter高阶组件包裹,才能拿到match和location这些props(v6的类型定义依然兼容RouteComponentProps,记得保证@types/react-router-dom版本和你安装的react-router-dom版本一致)。 - 要是还是有类型问题,可以检查一下你的路由配置是否和定义的参数类型匹配,比如路径参数有没有写错名称。
内容的提问来源于stack exchange,提问作者John Wong
相关产品推荐
相关产品推荐

