首页 > 解决方案 > 确切路径不会捕获 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。我究竟做错了什么?

标签: javascriptreactjs

解决方案


通过 slug 的一种方法是使用render()路线的。虽然可能有更清洁的方法,所以如果其他人对此有答案,我很乐意看到它!

  <Route exact
    path="/portfolio/:slug" 
    render={(props) => (<PortfolioDetail path={props.history.location.pathname} />)} 
  />

另一种方法是useParams这里描述的反应钩子:Using the useParams hook in react


推荐阅读