【问题标题】:Conditional rendering in React Router with Private and Public Routes使用私有和公共路由的 React Router 中的条件渲染
【发布时间】: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 ? &lt;PrivateRoute ... /&gt; : &lt;Route /&gt;
  • 根据authenticate 值在地图回调中有条件地呈现RoutePrivateRoute。或者,创建一个更通用的路由组件,该组件使用 auth 道具并进行条件渲染。请尝试更新您的问题以包含Minimal, Complete, and Reproducible Example
  • 顺便说一句,你应该小心! “authenticated”字段需要用户当前是否登录的信息,而不是路由是否是私有的。如果用户通过了身份验证,则传递 true,如果没有,则传递 false。

标签: javascript reactjs react-router


【解决方案1】:

您可以在私有路由中检查条件,如果它们不满足条件,您可以使用 useHistory hook 将它们发送到 404 或其他路由。

为此,您需要创建一个包含应用程序的上下文,并帮助您使用应用程序周围的数据。您可以使用本机反应功能,但您也可以使用 redux,这是我的首选,您可以使用 redux 进行状态管理。

页面中的代码会是这样的:

const history = useHistory();
if ({condistion}) {
    history.push({valid_route});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多