history.push() 和使用 react-router 的自定义 URL 参数 [英] history.push() and Custom URL parameters using react-router
问题描述
我正在尝试创建一个应用程序,用户可以在其中加入群组,其中一个页面是群组仪表板.为此,我创建了一个 URL 参数为 id 的路由.
<路由器><div><LoggedRoute 精确路径 = "/" 组件 = {Home}/><路由精确路径=/login"组件={Login}/><路由精确路径=/groups/:id"组件={GroupDash}/>
</路由器>
当用户创建一个组时,它会将它保存在我的数据库中,并获取 docID 用作 url 参数.
然后我使用 history.push("/groups/".concat(docID))
尝试将我的用户重定向到新页面.但是,这不起作用,而是将我带到 .../groups/
与 .../groups/docID
.
我最初认为这是因为字符串 docID
没有正确创建,但在将字符串记录到控制台后,它是正确的.
有人可以帮我吗?
您没有使用 开关
,我不知道为什么.以下是如何使用 URL 参数
在反应路由器中正确:
路线:
<路由器><开关>{/* 使用开关 */}<LoggedRoute 精确路径 = "/" 组件 = {Home}/><路由精确路径=/login"组件={Login}/><路由精确路径 = "/groups" 组件 = {Groups}/>{/* 这应该是准确的 */}<路由精确路径=/groups/:id"组件={GroupDash}/>{/* 对于这个用例,这个精确值是可选的 */}</开关></路由器>
你可以执行 history.push
去那条路线:
<按钮onClick={() =>{历史推送(`/组`)}}>团体按钮><按钮onClick={() =>{history.push(`/groups/${1234}`)}}>群组仪表板按钮>
要获取组件中的 id
,您可以使用 useParams
钩子或使用 withRouter
HOC(使用 props.match.params?.id
作为 HOC):
从 'react' 导入 React从'react-router-dom'导入{useParams}导出默认函数 GroupDash() {让 { id } = useParams()返回 <>Group Dash: {id}</>}
I'm trying to create an app where users can join groups, and one of the pages I have is a group dashboard. For this, I created a route with a URL parameter of id.
<Router>
<div>
<LoggedRoute exact path = "/" component = {Home}/>
<Route exact path = "/login" component = {Login}/>
<Route exact path = "/groups/:id" component = {GroupDash}/>
</div>
</Router>
When a user creates a group, it persists it in my database, and gets the docID to use as the url parameter.
I then use history.push("/groups/".concat(docID))
to attempt to re-direct my user to the new page. However, this doesn't work and instead takes me to .../groups/
vs .../groups/docID
.
I initially thought that this was because the string, docID
wasn't being created properly, but after logging the string to the console, it is correct.
Can someone help me with this?
You didn't use Switch
, I am not sure why. Here is how to use URL Parameters
correctly in react-router:
Routes:
<Router>
<Switch> {/* Use Switch */}
<LoggedRoute exact path = "/" component = {Home}/>
<Route exact path = "/login" component = {Login}/>
<Route exact path = "/groups" component = {Groups}/> {/* This should be exact */}
<Route exact path = "/groups/:id" component = {GroupDash}/> {/* This exact can be optional for this use case */}
</Switch>
</Router>
And you can do history.push
to go to that route:
<button
onClick={() => {
history.push(`/groups`)
}}
>
Groups
</button>
<button
onClick={() => {
history.push(`/groups/${1234}`)
}}
>
Groups dashboard
</button>
And to get the id
in your component, you can use useParams
hook or use withRouter
HOC (use props.match.params?.id
for the HOC):
import React from 'react'
import { useParams } from 'react-router-dom'
export default function GroupDash() {
let { id } = useParams()
return <>Group Dash: {id}</>
}
这篇关于history.push() 和使用 react-router 的自定义 URL 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!