我正在尝试创建一个用户可以加入群组的应用,而我拥有的页面之一是群组仪表板。为此,我创建了一个URL参数为id的路由。
<Router>
<div>
<LoggedRoute exact path = "/" component = {Home}/>
<Route exact path = "/login" component = {Login}/>
<Route exact path = "/groups/:id" component = {GroupDash}/>
</div>
</Router>
用户创建组时,会将其持久保存在我的数据库中,并获取docID用作url参数。
然后history.push("/groups/".concat(docID))
,我尝试尝试将用户重定向到新页面。然而,这并不工作,而是带我到.../groups/
VS .../groups/docID
。
最初,我认为这是因为docID
未正确创建字符串,但是在将字符串记录到控制台后,它是正确的。
有人可以帮我弄这个吗?
您没有使用Switch
,我不确定为什么。这是URL Parameters
在react-router中正确使用的方法:
路线:
<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>
您可以执行以下操作history.push
:
<button
onClick={() => {
history.push(`/groups`)
}}
>
Groups
</button>
<button
onClick={() => {
history.push(`/groups/${1234}`)
}}
>
Groups dashboard
</button>
为了获取id
组件中的in,可以使用useParams
hook或withRouter
HOC(props.match.params?.id
用于HOC):
import React from 'react'
import { useParams } from 'react-router-dom'
export default function GroupDash() {
let { id } = useParams()
return <>Group Dash: {id}</>
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句