You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React路由配置疑问:404错误路由渲染在内容区,应如何调整位置?

404路由的合适放置方案

根据你的需求,有两种常见的合理放置方式,对应不同的用户体验:

方案一:全屏独立404(推荐)

这种方式下,404页面完全脱离现有布局(不显示侧边栏、导航栏),全屏展示,更符合用户对“页面不存在”的认知。

修改后的代码结构如下:

import { Routes, Route, useLocation } from 'react-router-dom';

const Pages = () => {
  const location = useLocation(); // 用React Router钩子替代直接读取window.location

  return (
    <Routes>
      {/* 匹配所有有效路由,渲染带布局的内容 */}
      <Route path="/*" element={
        <>
          <Box display="flex">
            {location.pathname !== "/profile" && <Sidebar />}
            <Box flex={3}>
              <Navbar />
              <Routes>
                <Route exact path="/" element={<Dashboard />} />
                <Route exact path="/calendar" element={<Calendar />} />
                <Route exact path="/task" element={<div>Task</div>} />
                <Route exact path="/projects" element={<div>Projects</div>} />
                <Route exact path="/teamMember" element={<div>Team Member</div>} />
                <Route exact path="/profile" element={<Profile />} />
              </Routes>
            </Box>
          </Box>
        </>
      } />
      {/* 全局404,无布局全屏显示 */}
      <Route path="*" element={
        <div style={{
          width: '100vw',
          height: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '2rem'
        }}>
          404 - 页面不存在
        </div>
      } />
    </Routes>
  );
};

方案二:保留布局的404

如果希望404页面仍保留导航栏/侧边栏(方便用户跳转回其他页面),可以继续将404路由留在原位置,但优化内容区域样式让提示更清晰:

// 仅修改原Routes中的404路由
<Route path="*" element={
  <div style={{
    padding: '2rem',
    textAlign: 'center',
    fontSize: '1.5rem',
    color: '#666'
  }}>
    404 - 你访问的页面不存在,<a href="/">返回首页</a>
  </div>
} />

另外补充:原代码中用window.location.pathname判断侧边栏显示的方式不够React化,建议换成useLocation钩子,避免直接操作DOM对象,更符合React Router的使用规范。

内容的提问来源于stack exchange,提问作者Syndeecate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:18:17