javascript - 确切路径不会捕获 slug
问题描述
我正在学习一门课程,我正在为自己在 React 中构建一个投资组合。到目前为止,我所做的一切都有效,除了我遇到的这个问题。
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about-me" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/blog" component={Blog} />
<Route exact path="/portfolio/:slug" component={PortfolioDetail} />
<Route component={NoMatch} />
</Switch>
我有通过我已知的 slug 运行的开关,并且我的 NoMatch 正在捕获不存在的链接,除非我放置一个格式为 localhost:####/portfolio/non_existant_link 的链接。
投资组合详细代码:
import React from "react";
export default function(props) {
return (
<div>
<h2>Portfolio Detail for {props.match.params.slug}</h2>
</div>
);
}
无匹配码:
import React from "react";
import { Link } from 'react-router-dom';
export default function() {
return (
<div>
<h2>We couldn't find that page</h2>
<Link to="/">Return to homepage</Link>
</div>
);
}
讲师使用的是稍旧版本的 react。我究竟做错了什么?
解决方案
通过 slug 的一种方法是使用render()
路线的。虽然可能有更清洁的方法,所以如果其他人对此有答案,我很乐意看到它!
<Route exact
path="/portfolio/:slug"
render={(props) => (<PortfolioDetail path={props.history.location.pathname} />)}
/>
另一种方法是useParams
这里描述的反应钩子:Using the useParams hook in react
推荐阅读
- flutter - 颤振提供程序错误:在此小部件上方找不到正确的提供程序
- flutter - 如何解决 Flutter 上的 XMLHttpRequest 错误?
- javascript - 创建一个循环遍历每年并加载该年的数组
- database - 获取 PostgreSQL 错误的 sql 查询列表
- ios - 修复了 iframe 内的元素在 Safari iOS 中随滚动而移动
- javascript - 编辑网络首选项后远程仍未定义
- chromium - 如何在 RHEL 7 中安装最新的 chromium 版本?
- f# - 在代码引用中检索数组项
- python - 无法在需要 grad 的张量上调用 numpy()。改用 tensor.detach().numpy()
- twitter-bootstrap - 无法读取未定义的读取构造函数的属性