将路由参数传递给ReactJS构造函数会导致TS7006

时间:2018-01-20 10:55:20

标签: reactjs constructor react-router

我很难理解如何将路由参数传递给ReactJS。我有以下代码:

import * as React from "react";
import { RouteComponentProps } from "react-router";
import "isomorphic-fetch";

interface IFetchProject {
    project: IProject;
    loading: boolean;
}

export class Project extends React.Component<RouteComponentProps<{}>, IFetchProject> {
    constructor(props) {
        super(props);
        console.log("this.props", this.props);
        let project: IProject = {} as IProject;
        this.state = {
            project: project, loading: true
        };
        fetch("api/Projects/"+ this.props.match.params.id)
            .then(response => response.json() as Promise<IProject>)
            .then(data => {
                this.setState({ project: data, loading: false });
            });
    }
}

(由于此部分发生错误,因此省略了一些代码)

编译器抱怨constructor(props)出现此错误: TS7006 (TS) Parameter 'props' implicitly has an 'any' type.

基本的最终目标是在构造函数中访问route参数,这样我就可以使用该参数从我的API中获取正确的数据。

1 个答案:

答案 0 :(得分:0)

通过替换:

解决了问题
constructor(props) {

constructor(props: RouteComponentProps<{}>) {

不确定这是否是正确的方法,但它解决了我的问题。