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

React报错:Cannot read properties of undefined (reading 'params') 求助

问题原因与解决方法

错误Cannot read properties of undefined (reading 'params')的核心原因是你使用的React Router v6和教程里的旧版本(v5及以下)路由传参方式不兼容:

在React Router v5中,路由组件会自动接收match、location等props,但v6已经移除了这一机制,所以你的match参数是undefined,自然无法读取match.params.id。

修复步骤:

  1. 在houseinfo.js中导入React Router提供的useParams钩子
  2. 用useParams()替代原来的match.params获取URL参数

修改后的完整代码:

import React, { useState, useEffect } from 'react';
// 新增导入useParams
import { useParams } from 'react-router-dom';

const HouseInfo = () => {
  const [listings, setListings] = useState(null);
  // 使用useParams获取URL中的id参数
  const { id } = useParams();

  useEffect(() => {
    const fetchListings = async () => {
      try {
        const response = await fetch(`http://localhost:80/api/houseinfo/${id}`);
        const data = await response.json();
        setListings(data);
      } catch (error) {
        console.error('Error fetching house:', error);
      }
    };
    fetchListings();
  }, [id]);

  if (!listings) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>House Information</h1>
      <ul>
        <li>Title: {listings.title}</li>
        <li>Location: {listings.location}</li>
        <li>Price: {listings.price}</li>
      </ul>
    </div>
  );
};

export default HouseInfo;

额外说明:

你的路由配置<Route path="/houseinfo/:id" element={<HouseInfo />} />是符合React Router v6规范的,不需要修改,只需要调整组件内部获取参数的方式即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:32:42