如何解决尽管匹配精确路由,React Router 组件仍不呈现
我正在使用 React Router 构建一个简单的博客,但在更改位置时遇到了一些问题。
预期行为:
- Route localhost:8080/#/contact 应该显示 Contact 组件内容。
实际行为:
- Route localhost:8080/#/contact 不呈现 Contact 组件,而只呈现由 HomePage 组件呈现的 Pagination 组件导航链接 - 1、2、3。请注意下面代码中的注释。
也许与路径中的 :page 参数有关?我的第 1 条和第 5 条路线都在使用它。
额外问题:
- 如何在首页实现分页,不干扰其他路由?
- 登陆 localhost:8080/#/ 后,HomePage 组件显示博客文章的第一页,技术上应该位于 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>
</>
);
};
谢谢
解决方法
Switch 始终查看路由并呈现与您的路由匹配的第一条路由。
在本例中,您将 /:page
路由置于 Switch 的顶部。当 react router 查找您的路由时,它认为 "contact"
中的 "/contact"
字是页面 ID,它应该呈现 /:page
路由。
您应该将 /:page
路由放在“not found”之前,并尝试从路由中删除 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>
也尝试使用 <BrowserRouter>
而不是 Router。
希望您的问题得到解决。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。