You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中获取路由参数报错:类型'{}'不存在'id'属性

解决React+TypeScript中路由参数property 'id' does not exist on type '{}'的错误

这个问题我太熟了——TypeScript的静态类型检查在这里卡了你一下!默认情况下,match.params的类型被推断为空对象{},它不知道你在路由里定义了id这个参数,所以会抛出类型错误。下面给你几种靠谱的解决办法:

方法一:给组件Props定义明确的类型接口(类组件推荐)

先为路由参数定义类型,再让组件的Props继承RouteComponentProps并传入这个参数类型:

import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';

// 定义你的路由参数类型
interface FetchDataRouteParams {
  id: string; // 这里对应路由里的:id参数
}

// 组件的Props类型,结合路由组件的Props
interface FetchDataProps extends RouteComponentProps<FetchDataRouteParams> {}

export class FetchData extends React.Component<FetchDataProps> {
  render() {
    // 现在TypeScript能识别params里的id属性了
    const itemId = this.props.match.params.id;
    return (
      <div>
        当前获取的ID是:{itemId}
      </div>
    );
  }
}

方法二:直接使用泛型简化定义(适合参数少的场景)

如果你的路由参数比较简单,也可以不用单独定义接口,直接在RouteComponentProps里传入泛型参数:

import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';

export class FetchData extends React.Component<RouteComponentProps<{ id: string }>> {
  render() {
    const id = this.props.match.params.id;
    return <div>ID: {id}</div>;
  }
}

方法三:函数组件用useParams钩子(如果是函数组件的话)

如果你后续把组件改成函数式写法,用useParams的时候也可以指定类型:

import * as React from 'react';
import { useParams } from 'react-router-dom';

interface FetchDataParams {
  id: string;
}

export const FetchData = () => {
  // 给useParams传入参数类型
  const params = useParams<FetchDataParams>();
  return <div>当前ID:{params.id}</div>;
};

最后别忘了检查路由配置!

确保你的路由路径里确实定义了:id参数,比如:

<Switch>
  <Route path="/fetchdata/:id" component={FetchData} />
  {/* 其他路由... */}
</Switch>

如果路由里没写:id,就算类型定义对了,实际运行时也拿不到参数哦~

内容的提问来源于stack exchange,提问作者vkampouris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:50:39