我的react应用程序中有一个Router
组件。它将有4种不同类型的布局
1-没有布局的公共路由,如登录和注册
2-将具有UserLayout
组件的用户路由
3-将具有AdminLayout
组件的管理路由
4-除上述内容之外的任何内容都应呈现Error404
组件
这是我的Router
组件:
<BrowserRouter>
<Switch>
<Route path="/" exact render={() => <Redirect to='/user/signin' />} />
<Route path='/oauth/:token' component={Oauth} />
<Route path='/user/signin' component={Signin} />
<Route path='/admin/signin' component={Signin} />
<Route path='/user/signup/:username' component={Signup} />
<Route path='/user/signup' component={Signup} />
<Route path='/oauth' exact render={() => <Redirect to={'/user/dashboard'} />} />
<Route path='/user/reset' component={Reset} />
<ProtectedRoute path='/user/auth2fa' component={TwofactorForm} />
<ProtectedRoute path='/admin' exact component={Error404} />
<ProtectedRoute path='/user' exact component={Error404} />
<Route path='/user'>
<UserLayout>
<Switch>
//bunch of user routes
</Switch>
</UserLayout>
</Route>
<Route path='/admin'>
<AdminLayout>
<Switch>
//bunch of admin routes
</Switch>
</AdminLayout>
</Route>
<ProtectedRoute component={Error404} />
</Switch>
</BrowserRouter>
我的问题是404页。如果有人访问的/user*
URL与布局内的路由不匹配,他们将看到一个空的用户布局页面。/admin*
也是如此。如果我将Error404
组件嵌套在布局组件中Switch
的末尾,结果将是一个布局页面,其中包含404页,这不是我想要的。我怎样才能做到这一点?
重要提示:我不希望在URL更改时重新呈现布局组件。因为它们是有状态的,并且我使用头来连接到websocket,这对于在每次URL更改时重新连接到websocket来说并不理想
你不可能用简单的方法做到这一点。要解决这个问题,最好的方法是在从服务器获得的数据上添加一个条件,即如果数据为空,那么在您可以使用条件渲染并设置数据为空之后,您将返回一些显示该页面没有数据的jsx;
// if user select /user/23
{data?<div>empty ! </div>}
但是,如果你选择了像/usersdasa这样的路由,但没有发现任何错误或没有重定向到未找到的页面,你就必须用这种方法设置react路由器//如果用户选择/udsuasdusad
<Route path='*' component={notfound} />
并将其放在您的路由的末尾,当用户选择您的路由时,react路由器尝试将用户路由与您的路由相匹配,如果有任何路由不匹配,则他们找到了您的最后一条路由,该路由告诉react路由器所有路径应呈现未找到的组件