![](/img/trans.png)
[英]Is there a way to match routes in react-router-dom v6 based on whether the route exists in an object?
[英]No Match 404 route render on all routes: react-router-dom
我正在實現No Match route ,奇怪的是它正在使用每個指定的路由以及非指定的(它應該)呈現,所以它一直在呈現。
下面是一些需要研究的代碼: RouterNavigation 組件使用傳遞的數組生成<Route />
並在最后為 404 添加一個<Route />
。
<Fragment>
{RouteConfig.map((route, i) => (
<Route
render={({ location }) =>
route.isProtected ? (
isAuthenticated ? (
route.component
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
) : (
route.component
)
}
exact={route.path === "/" ? true : false}
path={route.path}
key={i}
/>
))}
<Route
key={RouteConfig.length}
path="*"
render={({ location }) => {
return (
<SuspenseContainer>
<PageNotFound from={location.pathname} />
</SuspenseContainer>
);
}}
/>
</Fragment>
在 App.tsx 代碼中導入我的 RouterNavigation 組件:
<Router>
<Switch>
<RouterNavigation />
</Switch>
</Router>
渲染后
更新:注意到的一件事是,當我們動態創建路由時,404 路由始終呈現,下面是包含來自 react-router-dom 的相同示例的 url,用於 404 路由幾乎沒有重構(即通過獲取 Route 部分並創建一個組件渲染它,就像我們所做的一樣)
https://codesandbox.io/embed/react-router-no-match-404-8eiv9?fontsize=14&hidenavigation=1&theme=dark
包json
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
代替Fragment
使用Switch
<Switch>
//routes go here
<Route ... />
...
</Switch>
這里: https : //codesandbox.io/s/react-router-no-match-404-bn9yg
Route
必須的直接子Switch
和Switch
之外RouterNavigation
是多余的,因此我們可以將其刪除:
<Router>
<RouterNavigation />
</Router>
在上面的 codesanbox 中編輯。
而不是使用
<Router>
<Switch>
<RouterNavigation />
</Switch>
</Router>
這應該有效,因為<Fragment>
允許您對子項列表進行分組,而無需向 DOM 添加額外的節點。
在相同的組件工作中使用
<Switch>
{RouteConfig.map((route, i) => (
<Route
render={({ location }) =>
route.isProtected ? (
isAuthenticated ? (
route.component
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
) : (
route.component
)
}
exact={route.path === "/" ? true : false}
path={route.path}
key={i}
/>
))}
<Route
key={RouteConfig.length}
path="*"
render={({ location }) => {
return (
<SuspenseContainer>
<PageNotFound from={location.pathname} />
</SuspenseContainer>
);
}}
/>
</Switch>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.