gpt4 book ai didi

javascript - React router - 具有固定值的路由中的参数

转载 作者:行者123 更新时间:2023-11-27 22:55:38 25 4
gpt4 key购买 nike

有没有办法用固定的值集定义动态路由?如果它不符合任何固定值,它将回退到下一条路线。我现在的情况是这样的 -

const routes = {
path: '',
component: AppComponent,
childRoutes: [
{ path: '/search/top', name: 'top', component: FixedSearchComponent},
{ path: '/search/new', name: 'new', component: FixedSearchComponent},
{ path: '/search', name: 'search', component: SearchComponent},
{ path: '/search/:query', name: 'search', component: SearchComponent},
]
}

但我想为其定义一个参数,例如 :fixedSearch ,并将其预定义为仅此值。也许是这样的?如果它不适合任何 topnew (或其他可能的集合),它将回退到 search

const routes = {
path: '',
component: AppComponent,
childRoutes: [
{ path: '/search/:fixedSearch', name: 'fixedSearch', fixedSearch: ['top', 'new'], component: FixedSearchComponent},
{ path: '/search', name: 'search', component: SearchComponent},
{ path: '/search/:query', name: 'search', component: SearchComponent},
]
}

最佳答案

您可以将 onEnter 函数附加到新路线,例如替换 /search/new/fixed/:fixedSearch/搜索/顶部。在 onEnter 函数内,您会将 :fixedSearch 与预定义值 (['top', 'new']) 进行比较,如果不存在的话如果不匹配,您可以回退到您的 /search 路线。这对于在允许访问路由之前检查用户是否经过身份验证很常见。

这是 onEnter 的文档:

onEnter(nextState, replace, callback?)

Called when a route is about to be entered. It provides the next router state and a function to redirect to another path. this will be the route instance that triggered the hook.

If callback is listed as a 3rd argument, this hook will run asynchronously, and the transition will block until callback is called.

一个粗略的示例(在 JSX 中)可能如下所示:

<Route path='/fixed/:fixedSearch' component={FixedSearchComponent} onEnter={checkFixedSearch} />

function checkFixedSearch(nextState, replace) {

if (*Compare :fixedSearch with predefined values*) {
replace('/search') // move to search route if fixed values don't match
}
}

关于javascript - React router - 具有固定值的路由中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649981/

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