【发布时间】:2021-01-26 08:50:10
【问题描述】:
如何根据 auth props 渲染组件?例如,我有一个 routes.js 文件,其中包含我的所有路由,包括私有和公共路由。
我想要一个包含所有路由的单个路由文件,无论它是私有组件还是公共组件,因为 home.js 稍后会检查这些。
以下是我的包含路线的路线文件:
import { Login, Register } from 'pages/form/components/';
import SecuredRoute from 'components/SecuredRoute';
const routes = [
{
path: '/',
authenticate: false,
component: Login
},
{
path: '/signup',
authenticate: false,
component: Register
},
{
path: '/secured1',
authenticate: true,
component: SecuredRoute
},
{
path: '/secured2',
authenticate: true,
component: SecuredRoute
}
];
export default routes;
下面是我在 Home.js 文件中渲染组件的 sn-p。
<Switch>
{routes.map((route, index) => {
return (
<PrivateRoute
exact
authenticated={route.authenticate}
path={route.path}
component={route.component}
key={index}
/>
);
})}
</Switch>
目前,我只能渲染私有组件,而不能渲染公共路由 问题:
- 如何在地图函数中检查路线是公共的还是私有的?正如您在 sn-p 中看到的,它只呈现私有组件,而不是公共组件。
【问题讨论】:
-
不要总是返回 PrivateRoute,而是返回
route.authenticate ? <PrivateRoute ... /> : <Route /> -
根据
authenticate值在地图回调中有条件地呈现Route或PrivateRoute。或者,创建一个更通用的路由组件,该组件使用auth道具并进行条件渲染。请尝试更新您的问题以包含Minimal, Complete, and Reproducible Example。 -
顺便说一句,你应该小心! “authenticated”字段需要用户当前是否登录的信息,而不是路由是否是私有的。如果用户通过了身份验证,则传递 true,如果没有,则传递 false。
标签: javascript reactjs react-router