如何在 React 中解决这个问题,让 <Outlet /> 正常工作?

问题描述 投票:0回答:1

我有一个 GameGuard 可以检查用户是否登录。如果是,您可以访问路线/game/*。我的问题是,如果您位于路径 /game 上,则会显示游戏组件的上下文,但如果您位于路径 /game/dashboard 上,则不会显示游戏组件的上下文,尽管实际上应该为两个路径显示相同的组件。 但是,如果您在 GameGuard 中将

return <Outlet />;
替换为
return <GameRouter />;
,则它可以工作。谁能解释一下为什么这不适用于 Outlet?

应用程序路由器:

const AppRouter = () => {
  return (
    <BrowserRouter>
      <Routes>

        <Route path="/game/*" element={<GameGuard />}>
          <Route path="/game/*" element={<GameRouter base="/game"/>} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

游戏卫士:

export const GameGuard = () => {
  if (localStorage.getItem("token")) {
    
    return <Outlet />;
  }
  
  return <Navigate to="/login" replace />;
};

游戏路由器:

const GameRouter = () => {
  return (
    <div style={{display: "flex", flexDirection: "column"}}>
      <Routes>

        <Route path="" element={<Game />} />

        <Route path="dashboard" element={<Game />} />

        <Route path="*" element={<Navigate to="dashboard" replace />} />

      </Routes>
   
    </div>
  );
};

我改变了这个:

        <Route path="/game/*" element={<GameGuard />}>
          <Route path="/game/*" element={<GameRouter base="/game"/>} />
        </Route

至:

        <Route path="/game/*" element={<GameGuard />}>
          <Route index element={<GameRouter base="/game"/>} />
        </Route

但是效果并不好。

reactjs react-router router-outlet
1个回答
0
投票

你不可能真的有两条匹配相同的路线。索引路由不能有子路由或渲染后代路由。

path="*" matches anything, while 
“*”` 附加到任何路径允许匹配后代路由。

以下路由配置有效:

  • GameGuard
    布局路由是无路径的,
    GameRouter
    路径使用通配符匹配器来允许匹配后代路由。

    <Routes>
      <Route element={<GameGuard />}>
        <Route path="/game/*" element={<GameRouter base="/game" />} />
      </Route>
    </Routes>
    
  • GameGuard
    布局路由使用路径
    "/game"
    GameRouter
    路径只是通配符匹配器,任何后代路由都可以匹配。

    <Routes>
      <Route path="/game" element={<GameGuard />}>
        <Route path="*" element={<GameRouter base="/game" />} />
      </Route>
    </Routes>
    
© www.soinside.com 2019 - 2024. All rights reserved.