Jon*_*nas 6 reactjs react-router react-router-dom
如何使用 React Router 附加到路由?
假设当前路线是/page1/page2,我想要路线到/page1/page2/next-page
首先我得到路由器
const router = useHistory();
Run Code Online (Sandbox Code Playgroud)
push当我这样使用时
router.push("next-page");
Run Code Online (Sandbox Code Playgroud)
它路由至/page1/next-page.
/当我使用像这样添加
router.push("/next-page");
Run Code Online (Sandbox Code Playgroud)
它路由至/next-page
我也尝试过这样的事情
router.push(`${router.location.pathname}/next-page`)
Run Code Online (Sandbox Code Playgroud)
但这样的问题是,当我目前处于 时/page1/page2/,我最终会得到/page1/page2//next-page两个//。
有没有一个好的方法可以解决这个问题,而不必像这样编写完整的路线router.push("/page1/page2/next-page")?
我最终做的是定义一个函数,该函数删除/表单 url(如果存在)
export const removeSlashSuffix = (input) => {
if (input.charAt(input.length - 1) === "/") {
return input.substr(0, input.length - 1)
} else {
return input;
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样路由
router.push(`${removeSlashSuffix(router.location.pathname)}/nest-page`)
Run Code Online (Sandbox Code Playgroud)
这样我就不会遇到在 url 中解析的路由问题//。
这有点像黑客解决方案,我希望react-router-dom开箱即用地支持它,但似乎并非如此
| 归档时间: |
|
| 查看次数: |
2988 次 |
| 最近记录: |