gpt4 book ai didi

javascript - React 路由器获取当前事件段作为参数

转载 作者:行者123 更新时间:2023-12-03 05:09:18 27 4
gpt4 key购买 nike

我有以下路由器配置

<Router history={history}>
<Route path="/" component={ReviewWizard}>
<IndexRoute component={Administrative}/>

<Route path="Administrative" component=Administrative}>
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>
</Route>
<Route path="Offense" component={Offense}/>
</Route>
</Router>

我正在尝试获取当前事件的路线段(即管理进攻)。

有没有办法做这样的事情?即路线约束

<Router history={history}>
<Route path="/:segment" component={ReviewWizard}>
<IndexRoute component={Administrative}/>

<Route path="/:segment=Administrative/:itemId" component={Administrative}>
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>
</Route>
<Route path="/:segment=Offense" component={Offense}/>
</Route>
</Router>

如果没有,获取当前事件路线段的最佳实践是什么?我不喜欢 this.context.router.routes[1].path

最佳答案

首先,我会推荐以下路由器配置,因为这似乎就是您的目标:

<Router history={history}>

<Route path="/" component={ReviewWizard}>

<!-- whenever we hit '/' we redirect to '/Administrative' -->
<IndexRedirect path="/Administrative"/>

<!-- Renders ReviewWizard <- Administrative -->
<Route path="/Administrative" component={Administrative}>

<!-- Renders ReviewWizard <- Administrative <- AdministrativeItem -->
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>

</Route>

<!-- Renders ReviewWizard <- Offense -->
<Route path="/Offense" component={Offense}/>

</Route>

</Router>

对于检测当前事件的路由(或者路由片段是否处于事件状态),我建议使用 the router.isActive -method 。只需做这样的事情:

if (router.isActive('/Administrative')) {
doSomething()
} else if (router.isActive('/Offense')) {
doSomethingElse()
}

对于更具声明性的内容,我建议仅使用 the location object react-router 注入(inject)到它管理的每个组件中:

const { location: { pathname } } = this.props
const [ activeSegment ] = pathname.slice(1).split('/')

希望这些有帮助!

关于javascript - React 路由器获取当前事件段作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com