首页 > 解决方案 > React 不会将组件渲染到使用动态路由的 url

问题描述

我正在尝试匹配 url 路径以执行动态路由,但组件未在路径处呈现。我在这里做错了什么?

顺便说一句,到 CollectionsOverview 组件的路由正在运行。

购买 Component.js:

https://imgur.com/Z7P4jjH


onst ShopPage = ({ match }) => {
  console.log(`Shop Component ${match.path}`);
  return (
    <div className='shop-page'>
      <Switch>
        <Route exact path={`/${match.path}`} component={CollectionsOverview} />
        <Route
          path={`/${match.path}/:collectionId`}
          component={CollectionPage}
        />
      </Switch>
    </div>
  );
};

export default ShopPage;


集合组件.js:

https://imgur.com/Wu36EAV

const CollectionPage = () => {
  console.log(`Collection Page`);
  return (
    <div className='collection-page'>
      <h2>Hello</h2>
    </div>
  );
};


结果:

https://imgur.com/UccQgB8

标签: reactjsreact-router

解决方案


/${match.path}/:collectionId在路径之前放置路径/${match.path}并从路径中删除exact

这是工作代码:https ://codesandbox.io/s/react-router-dynamic-routing-r714l

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";

const CollectionOverview = () => {
  return (
    <div>
      <div>CollectionOverview</div> <br />
      <Link to="/collection/1">To Collection 1</Link> <br />
      <Link to="/collection/2">To Collection 2</Link> <br />
      <Link to="/collection/3">To Collection 3</Link> <br />
      <Link to="/collection/4">To Collection 4</Link> <br />
    </div>
  );
};

const CollectionPage = props => {
  return <div>CollectionPage for ID: {props.match.params.id}</div>;
};

const HomeComponent = () => {
  return <div>Home Component</div>;
};

function App() {
  return (
    <BrowserRouter>
      <div>
        <Link to="/">To Home</Link>
        <br />
        <Link to="/collection">To Collection Overview</Link>
        <br />
      </div>
      <Switch>
        <Route path="/collection/:id" component={CollectionPage} />
        <Route path="/collection" component={CollectionOverview} />
        <Route path="/" component={HomeComponent} />
      </Switch>
    </BrowserRouter>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

推荐阅读