reactjs - React 不会将组件渲染到使用动态路由的 url
问题描述
我正在尝试匹配 url 路径以执行动态路由,但组件未在路径处呈现。我在这里做错了什么?
顺便说一句,到 CollectionsOverview 组件的路由正在运行。
购买 Component.js:
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:
const CollectionPage = () => {
console.log(`Collection Page`);
return (
<div className='collection-page'>
<h2>Hello</h2>
</div>
);
};
结果:
解决方案
/${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);
推荐阅读
- html - 悬停时 CSS 菜单不下拉
- azure - Azure WebApp AppSetting 没有覆盖我的 Web.Config 环境变量
- spring-boot - Rest API 请求路径使用 Apache camel 处理西班牙语文本
- ios - 读取二进制文件iOS时额外获取垃圾值
- angular - 备用的条件语法
- 角内
- vim - Coc.nvim 如何禁用 markdown 文件中的自动完成建议?
- docker - 是否可以在 Dockerfile 中创建 FROM 指令来拉取最新的图像?
- python - Pandas 布尔索引中的星号 (*)
- excel - 满足条件时将单元格值从一个工作表复制到另一个工作表
- javascript - 将对象添加到数组反应的末尾