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

React Router所有路由均显示404页面该如何排查解决?

问题原因

你遇到的错误是Switch组件使用不符合规范导致的:

  • Switch组件的作用是仅渲染第一个匹配到路径的Route或Redirect子元素,但你在Switch内部嵌套了一层<>(React Fragment),直接破坏了Switch的匹配逻辑,相当于Switch完全没有生效,所有路由规则都会被执行,因此匹配到对应页面路由的同时,也会命中path="*"的404路由,两个组件同时渲染。
  • 另外Navbar导航栏、FooterPage页脚属于全局公共布局组件,不需要参与路由匹配,不应该放在Switch内部。

修正后代码

import React from "react";
import Navbar from "./componentes/Navbar";
import './Estilos/EstilosGlobales.css'
import {ThemeProvider} from '@material-ui/core/styles'
import theme from './themeconfig'
import {BrowserRouter as Router,Switch,Route} from "react-router-dom";
import Inicio from "./Paginas/Inicio";
import FooterPage from "./componentes/FooterPage";
import AllCategorias from "./Paginas/AllCategorias.jsx"
import ErrorNoFount from "./Paginas/Error404";


function App() {
  return (
    <ThemeProvider theme={theme}>
      <Router>
        {/* 全局公共组件放在Switch外部,所有页面都会渲染 */}
        <Navbar />
        <Switch>
          {/* Switch内部仅放置需要匹配的Route组件 */}
          <Route path="/" exact component={Inicio} />
          <Route path="/categorias" component={AllCategorias} />
          <Route path="*" component={ErrorNoFount} />
        </Switch>
        <FooterPage />
      </Router>
    </ThemeProvider>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:12:01