我正在尝试迁移到使用 React Router 4,但在理解其逻辑时遇到了一些困难<Switch>
组件中使用的docs https://reacttraining.com/react-router/web/example/no-match处理 404(或不匹配)路由。
对于我的入口 JavaScript 文件,我设置了以下路由。
index.js
<Switch>
<Route path="/login" component={Login} />
<Route path="/forgot-password" component={ForgotPassword} />
<Route path="/email-verification" component={EmailVerification} />
<Route component={App} />
</Switch>
The Login
组件将检查用户是否通过身份验证,如果是,则将用户重定向到/dashboard
路线(通过history.replace
).
The App
仅当用户经过身份验证时才能访问组件,并且它具有类似的检查以将用户重定向到/login
如果她不是。
In my App
我有更多指定的路由,我可以确定只有在用户登录时才能访问这些路由。
App.js
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/accounts" component={Account} />
<Authorize permissions={['view-admin']}>
<Route path="/admin" component={Admin} />
</Authorize>
<Route path="/users" component={Users} />
<Route component={NotFound} />
</Switch>
这就是我的问题. The Authorize
组件检查传递的权限以查看用户是否具有这些权限,if so,它直接渲染孩子们,if not,它返回null
from render()
.
这里的预期行为是<Route path="/admin" />
当没有足够的权限并且<Route component={NotFound} />
组件渲染。
根据docs https://reacttraining.com/react-router/web/example/no-match:
A 呈现第一个匹配的子项。 A
没有路径总是匹配的。
但是,如果我去任何声明的路线after the <Authorize>
组件,路由器匹配null
。这意味着,根据上面的例子,/users
返回空值。反应路由器的预期行为是返回第一个匹配项<Switch/>
组件,即使它是一个null
value?
我怎样才能为这种情况提供“包罗万象”的路线(404)而不创建<PrivateRoute>
App.js 中每个经过身份验证的路由的组件?应该null
价值真的产生匹配吗?