在 ReactJS 中试图获取参数,但我得到属性 'id' 在类型 '' 上不存在

Posted

技术标签:

【中文标题】在 ReactJS 中试图获取参数,但我得到属性 \'id\' 在类型 \'\' 上不存在【英文标题】:In ReactJS trying to get params but I get property 'id' does not exist on type ''在 ReactJS 中试图获取参数,但我得到属性 'id' 在类型 '' 上不存在 【发布时间】:2018-10-07 10:44:51 【问题描述】:

这里是路线。我正在尝试获取 /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 组件看起来参数 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;

【问题讨论】:

看这里***.com/a/63660521/9161478 【参考方案1】:

对于钩子:

export interface IUserPublicProfileRouteParams 
    userId: string;
    userName: string;


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

【讨论】:

或者如果你不想导出接口,let id = useParams&lt; id: string &gt;();【参考方案2】:

使用 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);
;

【讨论】:

【参考方案3】:

你可以在RouteComponentProps的type参数中指定匹配到的路由参数的类型,这样替换掉错误就会消失

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

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

【讨论】:

以上是关于在 ReactJS 中试图获取参数,但我得到属性 'id' 在类型 '' 上不存在的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 reactjs 在 webapps 上获取特定的移动设备型号?

REACT JS:TypeError:无法读取未定义的属性“参数”

ReactJS - 使用查询参数获取路由

如何解决“未捕获的类型错误:无法读取未定义的属性'参数'”reactjs + django

在 ReactJS 中获取 onComponentDidMount 期间出现 CORS 错误

我不知道他们在这个实验中试图告诉我做什么