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

标签 reactjs typescript react-router

这是路线。我正在尝试获取像/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}?但我不确定如何做到这一点:/。有人可以帮我吗?我使用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;
}

最佳答案

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

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

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

关于reactjs - 在ReactJS中尝试获取参数,但我得到属性 'id'在类型 '{}'上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50047977/

相关文章:

javascript - 当我使用 <a> 标签跟随路线时,React-Router 正在刷新页面

javascript - react 路由器1.0错误: Uncaught TypeError: getCurrentLocation is not a function | createHistory. js

javascript - 使用 OpenLayers 3 作为 react 组件

javascript - 如何使用多个对象映射 API [Spree API V2 & ReactJS]

typescript - 与 Typescript Readonly 类型不一致

javascript - 在 typescript 中,拥有像这样的对象属性 "{ [x: string]: any }"意味着什么?

javascript - 在连接到状态不同部分的不同路由上重用 react/redux 组件

reactjs - 如何在react-router v5中正确包装路由?

javascript - ReactJS - 脚本 DOM 节点

typescript - 类型别名循环引用自身