【发布时间】:2021-07-06 07:29:46
【问题描述】:
我正在使用 React Router 构建一个简单的博客,但在更改位置时遇到了一些问题。
预期行为:
- Route localhost:8080/#/contact 应该显示 Contact 组件内容。
实际行为:
- Route localhost:8080/#/contact 不会渲染 Contact 组件,而只会渲染由 HomePage 组件渲染的 Pagination 组件导航链接 - 1、2、3。请注意下面代码中的注释。
也许它与路径中的 :page 参数有关?我的第 1 条和第 5 条路线都在使用它。
补充问题:
- 如何在首页实现分页,不干扰其他路由?
- 登陆 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