处理"未找到网页";使用React路由器



我的App.js组件是这样的

<Switch>
{loggedIn ?
<>
<div>
<DashboardLayout>
<Route path="/dashboard" component={Dashboard} />
<Route path="/my-account" component={Account} />
</DashboardLayout>
<Route path="/page-not-found" component={PageNotFound} />
<Redirect from='*' to='/page-not-found' />
</div>
</>
:
<PublicRoutes />}
</Switch>

我的dashboardLayout中有私有路由,我想让page-not-found显示在它上面,现在它显示在它下面。

我该如何解决这个问题?由于

根据react-router文档,Switch的子节点必须是RouteRedirect

您应该创建渲染组件的Routes,而不是其他方式。

编辑:我不确定是否React片段(<></>)是其中的一部分。你可能想测试它,或者有条件地渲染完全不同的Switch组件/子组件。

由于我无法在注释中包含所有内容,因此我将在这里添加更多内容....

我会这样想:

  1. 有一个可以访问签入/签出状态的组件。使用if/else,检查用户是否已登录并使用私有路由呈现Switch组件(如下所述),如果用户已注销,则使用公共路由呈现Switch组件(如下所述)。

  2. 每个Route组件都是上面有条件渲染的Switch中的顶层子组件。然后,这些路由组件会渲染一个包含特定于页面内容的"Page"组件。

  3. 然后每个页面呈现一个"Wrapper"组件,该组件具有页脚,注销按钮,图标等。

const WrapperComponent = ({ children })=>{
return (
<>
<div>
{/* ... Some content for the side bar ... */}
</div>
{children /* The page */}
</>
);
};
const SignInPage = ()=>{ /* ... */ };
const SignUpPage = ()=>{ /* ... */ };
const MyProfilePage = ()=>{ /* ... */ };
const SomePrivatePage = ()=>{
return (
<WrapperComponent>
{/* ... Some page-specific content ... */}
</WrapperComponent>
);
};
const MainSwitchComponent = ({ isSignedIn })=>{
if(isSignedIn){
return (
<Switch>
<Route path='/MyProfile'>
<MyProfilePage />
</Route>
<Route path='/SomePrivate'>
<SomePrivatePage />
</Route>
</Switch>
);
}
return (
<Switch>
<Route path='/SignIn'>
<SignInPage />
</Route>
<Route path='/SignUp'>
<SignUpPage />
</Route>
</Switch>
);
};

最终由你决定,但Route必须是顶级的。只要记住,根据文档,如果你在多个不同的路由下渲染相同的子组件,你需要在Route组件上使用keyprop。

一定要花时间从上到下阅读文档。我提到的大多数东西都在里面,并包括例子。

最新更新