ReactJS TS组件报错:match属性不存在于指定Props类型
嘿,这个问题我太熟了!你遇到的是TypeScript和React Router结合时常见的类型不匹配问题,我来给你捋捋怎么解决~
报错的核心原因是:你自定义的MyProps接口只声明了api属性,但你的组件是通过React Router渲染的,Router会自动给组件注入match、location、history这些路由相关属性,可TypeScript并不知道这些属性的存在,所以它会报错说match不在你的Props类型定义里。
下面是两种最常用的解决办法:
方法1:让自定义Props继承路由组件的Props类型
React Router提供了RouteComponentProps类型,它已经包含了所有路由相关属性的完整类型定义。你只需要让你的MyProps接口继承它就行:
import Api from '../../api/Api'; // 先从react-router-dom导入RouteComponentProps import { RouteComponentProps } from 'react-router-dom'; // 让MyProps继承RouteComponentProps,这样就包含了match等路由属性 interface MyProps extends RouteComponentProps { api: Api; } interface MyState { someString: string, loading: boolean } export class MyComponent extends React.Component<MyProps, MyState> { constructor(props: MyProps) { super(props); this.state = { someString: '', loading: false }; } componentDidMount() { // 现在访问this.props.match完全不会报错了 const urlParam = this.props.match.params.yourParamName; // 替换成你的URL参数名 // 后续业务逻辑... } // ...其他组件代码 }
方法2:使用交叉类型(不修改原接口的情况)
如果不想改动原有的MyProps接口,也可以在组件的Props泛型里用交叉类型把自定义Props和路由Props合并:
import Api from '../../api/Api'; import { RouteComponentProps } from 'react-router-dom'; interface MyProps { api: Api; } interface MyState { someString: string, loading: boolean } // 用&符号合并MyProps和RouteComponentProps export class MyComponent extends React.Component<MyProps & RouteComponentProps, MyState> { constructor(props: MyProps & RouteComponentProps) { super(props); this.state = { someString: '', loading: false }; } // ...同样可以正常访问this.props.match }
额外优化:精确指定URL参数类型
如果你想更精准地约束URL参数的类型,可以给RouteComponentProps传入泛型参数:
// 定义你的URL参数结构 interface UrlParams { id: string; category: string; } // 把UrlParams传给RouteComponentProps interface MyProps extends RouteComponentProps<UrlParams> { api: Api; } // 之后访问this.props.match.params.id时,TypeScript会自动识别它是string类型
这样处理后,TypeScript就能正确识别match属性的存在,报错自然就消失了,同时你也能安全地使用URL参数啦~
内容的提问来源于stack exchange,提问作者Sebastien
相关产品推荐
相关产品推荐

