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

vka*_*ris 15 typescript reactjs 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>;
Run Code Online (Sandbox Code Playgroud)

FetchData 组件看起来参数 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;
}
Run Code Online (Sandbox Code Playgroud)

Obl*_*sys 21

您可以在 的类型参数中指定匹配的路由参数的类型RouteComponentProps,因此如果您替换错误应该消失

class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {
Run Code Online (Sandbox Code Playgroud)

interface RouteParams {id: string, param2?: string}
class FetchData extends React.Component<RouteComponentProps<RouteParams>, FetchDataExampleState> {
Run Code Online (Sandbox Code Playgroud)


小智 18

对于钩子:

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

const {userId, userName} = useParams<IUserPublicProfileRouteParams>();
Run Code Online (Sandbox Code Playgroud)

  • 或者,如果您不想导出接口,`let { id } = useParams&lt;{ id: string }&gt;();` (9认同)