在ReactJS尝试获取参数但我得到属性'id'在类型'{}'上不存在

时间:2018-04-26 16:31:34

标签: reactjs typescript react-router

以下是路线。我试图获得像/ fetchdata / someid这样的参数,我尝试了this.props.match.params.id这就是说:

  类型“{}”

上不存在

属性“id”

import * as React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/containers/Home';
import FetchData from './components/FetchData';
import { Counter } from './components/Counter';

export const routes =
    <Layout>  
        <Route exact path='/' component={Home} />
        <Route path='/counter' component={Counter} />
        <Route path='/fetchdata/:id/:param2?' component={FetchData} />    
    </Layout>;

FetchData组件看起来param id在匹配中但我无法得到它。 :/我想我错过了{match}?但我不确定如何做到:/。有人可以帮帮我吗?我使用react-router“:”4.0.12“。

import * as React from 'react';
import { RouteComponentProps, matchPath } from 'react-router';
import 'isomorphic-fetch';
//import FetchDataLoaded from './FetchDataLoaded';
import { withRouter } from 'react-router-dom';
import queryString from 'query-string';

interface FetchDataExampleState {
    forecasts: WeatherForecast[];
    loading: boolean;
    lazyloadedComponent;
    id;
}
//const queryString = require('query-string');

class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {
    constructor(props) {
        super(props);

        this.state = { forecasts: [], loading: true, lazyloadedComponent: <div>Getting it</div>, id: "" };

        fetch('api/SampleData/WeatherForecasts')
            .then(response => response.json() as Promise<WeatherForecast[]>)
            .then(data => {
                this.setState({ forecasts: data, loading: false });
            });
    }

    async componentDidMount() {
        try {
            //let params = this.props.match.params
            //const idquery = queryString.parse(this.props.location .).id;
           //const idquery = queryString.parse(this.props.match.params).id;
            //const idquery = this.props.match.params.id;
            const idParam = this.props.match.params.id
            this.setState({
                id: idParam                
            })
            const lazyLoadedComponentModule = await import('./FetchDataLoaded');
            this.setState({ lazyloadedComponent: React.createElement(lazyLoadedComponentModule.default) })
        }
        catch (err) {
            this.setState({
                lazyloadedComponent: <div>${err}</div>
            })
        }    
    }    
    public render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : FetchData.renderForecastsTable(this.state.forecasts);

        return <div>
            <div>Id: {this.state.id}</div>
            {this.state.lazyloadedComponent}
            <h1>Weather forecast</h1>
            <p>This component demonstrates fetching data from the server.</p>
            {contents}
        </div>;
    }

    private static renderForecastsTable(forecasts: WeatherForecast[]) {

        return <table className='table'>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                {forecasts.map(forecast =>
                    <tr key={forecast.dateFormatted}>
                        <td>{forecast.dateFormatted}</td>
                        <td>{forecast.temperatureC}</td>
                        <td>{forecast.temperatureF}</td>
                        <td>{forecast.summary}</td>
                    </tr>
                )}
            </tbody>
        </table>;
    }
}
export default withRouter(FetchData)
interface WeatherForecast {
    dateFormatted: string;
    temperatureC: number;
    temperatureF: number;
    summary: string;
}

3 个答案:

答案 0 :(得分:6)

对于钩子:

export interface IUserPublicProfileRouteParams {
    userId: string;
    userName: string;
}

const {userId, userName} = useParams<IUserPublicProfileRouteParams>();

答案 1 :(得分:2)

您可以在RouteComponentProps的类型参数中指定匹配的路线参数的类型,因此如果您更换

,错误就会消失
class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {

interface RouteParams {id: string, param2?: string}
class FetchData extends React.Component<RouteComponentProps<RouteParams>, FetchDataExampleState> {

答案 2 :(得分:0)

使用React Function组件可以工作:

import React from "react";
import { match } from "react-router-dom";

export interface AuditCompareRouteParams {
  fileType: string;
}

export const Compare = ({ match }: { match: match<AuditCompareRouteParams> }) => {
  console.log(match.params.fileType);
};