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

React Router通配符路由为何始终渲染?如何实现404页面效果

问题原因及解决办法

问题根源

React Router 的 <Route> 组件默认是匹配即渲染的模式——只要当前 URL 和 path 属性的规则能匹配上,这个组件就会被渲染,不会自动排除其他匹配的 Route。

你现在的代码里没有用 <Switch> 组件包裹所有路由规则,所以:

  • 当 URL 是 / 时,path="/"(带exact)和path="*"都匹配,Home 和 PageTwo 会同时渲染
  • 当 URL 是 /pageone 时,path="/pageone"和path="*"都匹配,PageOne 和 PageTwo 会同时渲染

path="*" 是通配规则,能匹配任何 URL,所以只要没做排他处理,它就会一直被渲染。

解决办法

用 React Router 提供的 <Switch> 组件包裹所有 <Route>,<Switch> 的特性是只渲染第一个匹配成功的 Route,这样就能实现「前面的路由都不匹配时才渲染404页面」的效果。同时要把path="*"的Route放在最后,确保它是最后一个被匹配的选项。

修改后的代码如下:

// Import stuff using this syntax specifically for CodePen
const { HashRouter, Route, Link, Switch } = ReactRouterDOM;

const Home = () => (
  <div class="container">
    <h1>Home</h1>
    <Link to="/pageone">Page 1</Link>
    <Link to="/pagetwo">Page 2</Link>
  </div>
);

const PageOne = () => (
  <div class="container">
    <h1>Page 1</h1>
  </div>
);

const PageTwo = () => (
  <div class="container">
    <h1>Page 2 (404)</h1>
  </div>
);

const App = () => (
  <HashRouter>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/pageone" component={PageOne} />
      <Route path="*" component={PageTwo} />
    </Switch>
  </HashRouter>
);

这样修改后,只有当 URL 不是 / 或 /pageone 时,才会触发最后一个path="*"的Route,渲染PageTwo作为404页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:53:11