ReactJS TS,类型“ Readonly <{children?:ReactNode}>和Readonly <MyProps>”上不存在属性“ match”

Seb*_*ien 7 typescript reactjs

我试图输入组件的属性并同时使用URL参数。我收到以下错误:

类型“ Readonly <{children?:ReactNode}>和Readonly”上不存在属性“ match”

这是我的一些代码:

import Api from '../../api/Api';

interface MyProps {
    api: Api
}

interface MyState {
    someString: string,
    loading: boolean
}

export class MyComponent extends React.Component<MyProps, MyState> {

    constructor(props: MyProps) {
        super(props);
        this.state = {
            someString: this.props.match.params.someString,//<-- Error is here on this line
            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 (
            <div>
                <p>{this.someString}</p>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试做的是:

1-转到:

http:// localhost:8080 / someStrings /:someString

2-在组件的构造函数中获取:someString的值并存储在状态中

3-在我的状态下使用someString的值,以将其作为参数传递给我的API模块以进行操作

4-当在API中执行回调时,我删除了加载动画

我的问题基本上是,如何声明我的MyProps能够实现这一目标?

Rit*_*Dey 7

这是类型定义中的未解决问题。https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17355

解决方法

import { RouteProps } from 'react-router';
import React from 'react';

interface MyProps {
    api: Api
}

interface MyState {
    someString: string,
    loading: boolean
}

class MyComponent extends React.Component<Props & RouteProps, State> // Pay attention here.
{
  // your code...
}
Run Code Online (Sandbox Code Playgroud)

参考:https : //github.com/DefinitelyTyped/DefinitelyTyped/issues/17355#issuecomment-336022780


小智 6

这就是我解决它的方法

import {RouteComponentProps} from 'react-router';
interface IMyProps {}

interface IReactRouterParams {
  roomName: string;
  username: string;
}
export class MyComponent extends React.Component<
  IMyProps & RouteComponentProps<IReactRouterParams> {
 
  constructor(props: any) {
    super(props);
    //everything works here
    const {roomName, username} = this.props.match.params;
  }
}
Run Code Online (Sandbox Code Playgroud)