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

react-router-dom v5 保护路由触发404及404独立UI实现问题咨询

配置错误说明

  1. App组件中Switch的路由顺序错误:react-router-dom v5的Switch会按从上到下的顺序匹配路由,命中第一个符合规则的路由后就会终止后续匹配。你将NotFound路由放在Layout之前,所有非登录/注册/忘记密码的路径都会直接命中404,根本不会执行到Layout的逻辑,自然无法匹配到受保护路由。
  2. Layout没有被包裹在Route组件内,直接放在Switch中不属于合法的路由匹配规则,逻辑执行会异常。

解决方案

我们可以新增一个独立的/404路由用来渲染无Layout的404页面,嵌套路由中没有匹配到路径时统一重定向到该路由即可,完整修正代码如下:

1. 修正App组件路由结构

function App() {
  return (
    <Router>
      <AuthContextProvider>
        <Switch>
          <Route exact path="/login" component={Login} />
          <Route exact path="/forgot" component={Forgot} />
          <Route exact path="/signup" component={SignUp} />
          {/* 独立404路由,放在Layout之前,命中直接渲染无Layout的404页面 */}
          <Route exact path="/404" component={NotFound} />
          {/* 所有需要带Layout的路由,不加exact匹配所有/开头的路径 */}
          <Route path="/">
            <Layout>
              <Routing />
            </Layout>
          </Route>
        </Switch>
      </AuthContextProvider>
    </Router>
  );
}

2. 修正Routing组件嵌套路由

const Routing = () => {
  return (
    <Switch>
      <ProtectedRoute exact path="/" component={Home} />
      {/* 其他所有受保护路由按顺序放在这里 */}
      <ProtectedRoute exact path="/dashboard" component={Dashboard} />
      {/* 所有未匹配到的受保护路由路径,统一重定向到独立404页面 */}
      <Route>
        <Redirect to="/404" />
      </Route>
    </Switch>
  );
}

3. 原有ProtectedRoute逻辑无需修改

function ProtectedRoute({ component: Component, ...rest }) {
  const { currentUser } = useAuth();

  return (
    <Route
      {...rest}
      render={(props) => {
        return currentUser ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        );
      }}
    ></Route>
  );
}

执行逻辑说明

  • 访问公开路由(登录/注册/忘记密码/404):直接命中对应路由,不会渲染Layout,样式独立
  • 访问合法受保护路由:命中Layout路由后,进入嵌套路由匹配到对应组件,带Layout结构渲染
  • 访问不存在的路径:嵌套路由匹配失败后重定向到/404,渲染独立的404页面,不会继承Layout结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:06:04