ReactJS TS,类型'Readonly<{children?:ReactNode}> & Readonly'上不存在属性'match'。
ReactJS TS,类型'Readonly<{children?:ReactNode}> & Readonly'上不存在属性'match'。
我正在尝试在输入组件的同时使用URL参数。我得到了以下错误:
属性“match”在类型“Readonly<{children?:ReactNode}> & Readonly”上不存在
这是我的一部分代码:
import Api from '../../api/Api'; interface MyProps { api: Api } interface MyState { someString: string, loading: boolean } export class MyComponent extends React.Component{ constructor(props: MyProps) { super(props); this.state = { someString: this.props.match.params.someString,//<-- 错误发生在这行 loading: true } } componentDidMount() { this.props.api.getSomeInfo(this.state.someString, this.callback) } callback() { let interval = setInterval(function () { this.setState({loading: false}); clearInterval(interval) }, 3000); } render() { return ( {this.someString} ); } }
如您所见,我所尝试做的只是:
1- 转到:
2- 在我的组件构造函数中获取:someString的值并存储在state中
3- 使用state中的someString值作为参数传递给我的API模块以执行操作
4- 当API中的回调函数执行时,移除加载动画
我的问题基本上是,如何声明我的MyProps以实现这一目标?
问题原因:在React组件中,使用了match属性,但是类型检查器无法找到match属性的定义,导致报错。
解决方法:在组件的props中添加RouteComponentProps接口,并将其与原有的props类型进行合并。
具体步骤如下:
1. 将组件的定义从`export class MyComponent extends React.Component
2. 这样做可以将RouteComponentProps接口中定义的属性添加到组件的props中,包括match属性。
3. 这个解决方法在React 16.6和TypeScript 3.1.3版本中适用。
代码示例:
import { RouteComponentProps } from 'react-router-dom'; interface MyProps { // 组件的其他属性 } interface MyState { // 组件的状态 } export class MyComponent extends React.Component{ // 组件的实现 }
以上就是解决React组件中出现"Property 'match' does not exist on type"错误的方法。
ReactJS TS中出现"Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly
解决这个问题的一个解决方法是在组件定义时使用
import { RouteProps } from 'react-router';
import React from 'react';
interface MyProps {
api: Api
}
interface MyState {
someString: string,
loading: boolean
}
class MyComponent extends React.Component
{
// your code...
}
这样,在组件中就可以通过this.props.match.params来访问params参数了。具体的访问路径可以在JSX的render方法中使用,如下所示:
this.props.match.params
更多关于这个的问题可以参考https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17355#issuecomment-336022780。
以上是关于ReactJS TS中"Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly
在这个问题中,出现了一个类型错误,错误信息为"Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly
这个问题的原因是在MyComponent组件中,我们试图从props中访问'match'属性,但是类型定义中并没有包含'match'属性。
解决这个问题的方法是添加RouteComponentProps泛型到MyComponent组件的props类型中。RouteComponentProps是一个React Router提供的类型,用于传递路由参数和其他相关信息。
在解决方法中,我们首先从'react-router'模块中导入RouteComponentProps。然后,我们定义了一个新的接口IReactRouterParams,该接口包含了我们在路由中定义的参数。接着,我们将RouteComponentProps泛型应用到IMyProps接口,使MyComponent组件的props类型包含路由参数。最后,在MyComponent组件的构造函数中,我们可以通过this.props.match.params来访问路由参数。
通过这样的修改,我们成功解决了"Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly