【问题标题】:React Switch always going to first RouteReact Switch 总是去第一条路线
【发布时间】:2021-04-30 23:00:05
【问题描述】:

如果我点击“/”或“/reset_password”或任何其他路由,PurelyUnauthenticatedRoutes 中的第一个组件总是会被调用,即带有消息 ROUTE_CONSTANTS.RESET_PASSWORD 的 PublicRoute

<Router>
         <Switch>
           <PurelyUnauthenticatedRoutes />
           <PublicRoute key={1} redirect={false} path="/" component={CheckAuthenticatedRoutes} />
         </Switch>
     </Router>

const PurelyUnauthenticatedRoutes = (props) => {
  return [
    <PublicRoute
      {...props}
      key={"/reset_password"}
      redirect={false}
      path={"/reset_password"}
      render={(routeProps) => <div>{ROUTE_CONSTANTS.RESET_PASSWORD}</div>}
    />,
  ];
};
const PublicRoute = (props) => {

  const { userAuthenticationDetails, redirect } = props;

  const isLoggedIn = (userAuthenticationDetails && userAuthenticationDetails.isLoggedIn) || false;
  if (isLoggedIn && redirect) {
    return <Redirect to={"/dashboard"} />;
  }
  return <Route {...props} />;
};

export default PublicRoute;

【问题讨论】:

  • 你应该在路由上使用 exact 属性,否则它只会匹配第一个匹配的:reactrouter.com/web/api/Route/exact-bool
  • @Jayce444 我应该在哪里以及为什么要准确放置。理想情况下,如果我要说“/”,那么它应该转到 CheckAuthenticatedRoutes 组件,但它会转到 PurelyUnauthenticatedRoutes 第一个元素

标签: reactjs routes react-router router


【解决方案1】:

这是您的PurelyUnauthenticatedRoutes 组件上的return 语句执行此操作。您正在返回一个 PublicRoute 组件数组。 React 不知道如何正确渲染它。相反,您应该将多个路由作为 Switch 组件的子级返回。

Router 中有多个Switch 语句很好。所有Route 组件都必须是Switch 的直接子级(除非您要渲染多个Routes)。

您确实需要弄清楚您的匹配条件,因为Router 顶层的Switch 意味着流量将流向PurelyUnauthenticatedRoutesPublicRoute - 而不是两者。目前所有流量都由PurelyUnauthenticatedRoutes 处理,因此PublicRoute 组件与key={1} 永远不会显示。

const PurelyUnauthenticatedRoutes = (props) => {
  return (
    <Switch>
      <PublicRoute
        {...props}
        key={"/reset_password"}
        redirect={false}
        path={"/reset_password"}
        render={(routeProps) => <div>{ROUTE_CONSTANTS.RESET_PASSWORD}</div>}
      />
    </Switch>
  );
};

注意:当您在 App 中使用 props 时,您当前没有使用任何 props 调用它,因此您实际上不需要接受或传递该 props 对象,如果您不这样做想要。

【讨论】:

  • 我尝试在 PurelyUnauthenticatedRoutes 中添加开关,但主父开关仍然总是转到第一条路由,即 PurelyUnauthenticatedRoutes。它不会检查是否没有具有该名称的路由,所以转到下一条路由。此外,如果我通过路径支持 PurelyUnauthenticatedRoutes 它工作正常。但我不能有一系列路径作为 PurelyUnauthenticatedRoutes 的支持。因为它不会是正确的方法
猜你喜欢
  • 2011-03-07
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 2020-02-03
相关资源
最近更新 更多