javascript - 未使用 react-router 匹配的自定义组件
问题描述
我试图将关注点与我的路线分开,让我的反应代码更有条理。我目前正在使用react-router-dom
v5。
我有一个Application Routes
包含 3 个子组件的组件
AuthenticatedRoutes
PublicRoutes
Error404Route
每个组件呈现不同的路由/组件,但只有第一个组件 ( AuthenticatedRoutes
) 被匹配。
申请途径
export const ApplicationRoutes = () => (
<Switch>
<AuthenticatedRoutes />
<PublicRoutes />
<Error404Route />
</Switch>
);
认证路由
export const AuthenticatedRoutes = () => (
<Switch>
<Route exact path='/dashboard'>
<Dashboard />
</Route>
<Route exact path='/profile'>
<Profile />
</Route>
</Switch>
);
公共路线
export const PublicRoutes = () => (
<Switch>
<Route exact path='/about'>
<About />
</Route>
<Route exact path='/'>
<Home />
</Route>
</Switch>
);
错误路线
export const Error404Route = () => (
<Switch>
<Route>
<Error404 />
</Route>
</Switch>
);
所以,我是说只有AuthenticatedRoutes
(/dashboard
和/profile
) 被匹配,公共路由和error404路由不是。
我认为如果您使用 Switch 路由将尝试匹配位置路径名,如果不匹配,则会显示 Error404Route。
我错过了什么吗?(当然我是)
谢谢!
解决方案
试试这样:
申请途径
import AuthenticatedRoutes from './AuthenticatedRoutes'
import PublicRoutes from './PublicRoutes'
import Error404Route from './Error404Route'
export const ApplicationRoutes = () => (
<Switch>
{AuthenticatedRoutes}
{PublicRoutes}
{Error404Route}
</Switch>
);
认证路由
import Dashboard from './Dashboard'
import Profile from './Profile'
export const AuthenticatedRoutes = [
<Route exact path='/dashboard' component={Dashboard}/>,
<Route exact path='/profile' component={Profile}>,
];
公共路线
import Home from './Home'
import About from './About'
export const PublicRoutes = [
<Route exact path='/' component={Home}/>,
<Route exact path='/about' component={About}>,
];
错误路线
import Error404 from './Error404'
export const Error404Route = [
<Route exact path='/' component={Error404}/>,
];
推荐阅读
- haskell - Haskell 图:方向固定的箭头
- python - 如何解决这部分程序中的这个关键错误
- algorithm - 在棋盘上移动 N 个国王
- jsf - 问题 Primefaces + JSF 这个 XML 文件似乎没有任何与之关联的样式信息
- c# - 一个单元格中有多行的 SQL 子字符串问题
- steam - Steam API/JSON 中的物品买卖订单
- reactjs - Stackblitz 错误:找不到包:firebase
- php - 基于 React 的 WordPress 插件调试基本原理
- python - 带有 numpy 功能的 Numba cc 导出不起作用
- c# - 搜索时找不到图像 [在位图中搜索位图]