开发者问题收集

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

2018-04-26
14249

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

property 'id' does not exist on type '{}'

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 组件看起来参数 id 在 match 中,但我无法获取它。:/ 我想我忘了传递 {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个回答

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

class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {

替换为

interface RouteParams {id: string, param2?: string}
class FetchData extends React.Component<RouteComponentProps<RouteParams>, FetchDataExampleState> {
,错误就会消失
Oblosys
2018-04-26

对于钩子:

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

const {userId, userName} = useParams<IUserPublicProfileRouteParams>();
Stanislav Glushak
2020-09-26

使用 React 函数组件可以实现以下效果:

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);
};
Gus
2019-06-27