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

React嵌套路由组件不渲染:match.path未定义报错求助

问题解决:React Router 嵌套路由报错Cannot read properties of undefined (reading 'path')

报错根源

你用的是React Router v6,但代码还是v5的写法:

  1. v6不再给路由组件自动注入match、history等props,所以ShopPage组件的match参数是undefined,访问match.path直接报错。
  2. v6要求所有Route必须包裹在Routes组件内,不能像v5那样直接嵌套。

解决方案(两种可选)

方案1:用useMatch钩子适配现有结构

修改ShopPage组件,通过useMatch获取当前路由路径,同时用Routes包裹子路由:

import React from 'react';
import { Route, Routes, useMatch } from 'react-router-dom';

import CollectionsOverview from '../../components/collections-overview/collections-overview.component';
import CollectionPage from '../collection/collection.component';

const ShopPage = () => {
  // 匹配ShopPage对应的父路由路径,根据你的实际路由配置调整
  const match = useMatch('/shop');

  return (
    <div className='shop-page'>
      <Routes>
        {/* 用可选链避免match为undefined时的报错 */}
        <Route path={`${match?.path}`} element={<CollectionsOverview />} />
        <Route path={`${match?.path}/:collectionId`} element={<CollectionPage />} />
      </Routes>
    </div>
  );
};

export default ShopPage;

修改CollectionPage组件,用useParams获取路由参数(v6不再用match.params):

import React from "react";
import { useParams } from 'react-router-dom';
import CollectionItem from "../../components/collection-item/collection-item.component";
import './collection.styles.scss';

const CollectionPage = () => {
  const { collectionId } = useParams();
  console.log(collectionId);

  return (
    <div className="category">
      <h2>CATEGORY PAGE: {collectionId}</h2>
    </div>
  )
}

export default CollectionPage;

方案2:用v6推荐的嵌套路由结构(更规范)

先在根路由配置(比如App.jsx)中定义嵌套路由:

import { Routes, Route } from 'react-router-dom';
import ShopPage from './pages/shop/shop.component';
import CollectionsOverview from './components/collections-overview/collections-overview.component';
import CollectionPage from './pages/collection/collection.component';

function App() {
  return (
    <Routes>
      {/* 其他路由 */}
      <Route path="/shop" element={<ShopPage />}>
        {/* index路由对应父路由的默认渲染(/shop) */}
        <Route index element={<CollectionsOverview />} />
        {/* 子路由对应/shop/:collectionId */}
        <Route path=":collectionId" element={<CollectionPage />} />
      </Route>
    </Routes>
  );
}

然后简化ShopPage组件,用Outlet渲染匹配的子路由:

import React from 'react';
import { Outlet } from 'react-router-dom';

const ShopPage = () => (
  <div className='shop-page'>
    {/* Outlet会自动渲染匹配的子路由组件 */}
    <Outlet />
  </div>
);

export default ShopPage;

CollectionPage组件的修改和方案1一致,用useParams获取参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:12:59