【问题标题】:React Router component doesn't render despite matching exact route尽管匹配了确切的路线,但 React Router 组件不会呈现
【发布时间】:2021-07-06 07:29:46
【问题描述】:

我正在使用 React Router 构建一个简单的博客,但在更改位置时遇到了一些问题。

预期行为:

  1. Route localhost:8080/#/contact 应该显示 Contact 组件内容。

实际行为:

  1. Route localhost:8080/#/contact 不会渲染 Contact 组件,而只会渲染由 HomePage 组件渲染的 Pagination 组件导航链接 - 1、2、3。请注意下面代码中的注释。

也许它与路径中的 :page 参数有关?我的第 1 条和第 5 条路线都在使用它。

补充问题:

  1. 如何在首页实现分页,不干扰其他路由?
  2. 登陆 localhost:8080/#/ 后,主页组件显示博客文章的第一页,技术上应该在 localhost:8080/#/1 上。有没有我可以使用的合乎逻辑的解决方法?

我的应用组件:

import {
    HashRouter as Router, Route, Switch, Redirect
} from 'react-router-dom';
const App = () => {
        const routes = (
            <Switch>
                <Route exact path="/" component={HomePage} />
                <Route exact path="/:page?" component={HomePage} /> // commenting this line out causes <Contact /> work properly, but then again pagination on HomePage doesn't work as I don't have parameter in the url.
                <Route exact path="/post/:uid" component={PostPage} />
                <Route exact path="/contact" component={ContactPage} />
                <Route exact path="/category/:category/:page?" component={CategoryPage} />
                <Route component={NotFoundPage} />
            </Switch>
        );
    
        return (
            <>
               <MetaDecorator/>
               <Router>
                 {routes}
               </Router>
            </>
        );
    };

谢谢

【问题讨论】:

  • 为什么在你的例子中使用#?这在 React 中不是必需的,如果您实际上将链接指向“#/contacts”,则它将不起作用。
  • 我使用HashRouter作为Router,所以是这个原因。

标签: reactjs parameters routes blogs


【解决方案1】:

Switch 始终查看路由并呈现与您的路由匹配的第一条路由。

在本例中,您将/:page 路由置于交换机的顶部。当 react 路由器查找你的路由时,它认为 "/contact" 中的 "contact" 单词是一个页面 id,它应该呈现 /:page 路由。

您应该将/:page 路由放在“未找到”之前,并尝试从您的路由中删除exact 关键字,/ 除外。

return (
  <Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/post/:uid" component={PostPage} />
    <Route path="/contact" component={ContactPage} />
    <Route path="/category/:category/:page?" component={CategoryPage} />
    <Route path="/:page?" component={HomePage} />
    <Route component={NotFoundPage} />
  </Switch>
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

同时尝试使用&lt;BrowserRouter&gt; 代替路由器。

希望您的问题能得到解决。

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2018-02-27
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2021-08-10
    相关资源
    最近更新 更多