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

React-Router 6.2.1中URL不匹配任何路由时错误页面元素配置问题

Fixing "No routes matched location" Warning with Custom 404 Page in React Router v6

Hey there! I can help you fix that warning while getting your custom ErrorPage working correctly for unmatched routes.

The Issue

In React Router v6, just adding a <Route> without a path prop won’t properly catch all unmatched locations — that’s why you’re still seeing the "No routes matched location" warning. You need to explicitly tell the router to match any path that hasn’t been handled by the previous routes.

The Fix

Add path="*" to your error route. This special path pattern matches any URL that doesn’t match the routes defined above it. Here’s how to update your code:

Modified Routes Section

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/news" element={<News />} />
  <Route path="/contact" element={<Contact />} />
  {/* Add path="*" to catch all unmatched routes */}
  <Route path="*" element={<ErrorPage />} />
</Routes>

Full Updated Code

import React, { Component } from "react";
import { BrowserRouter as Router, NavLink, Route, Routes, } from "react-router-dom";
import "./App.css";

const Home = () => <h1>Home</h1>;
const News = () => <h1>News</h1>;
const Contact = () => <h1>Contact</h1>;
const ErrorPage = () => <h1>Page not found</h1>;

class App extends Component {
  state = {};
  render() {
    return (
      <Router>
        <div>
          <header>
            <nav>
              <ul>
                <li>
                  <NavLink to="/">Home</NavLink>
                </li>
                <li>
                  <NavLink to="/news">News</NavLink>
                </li>
                <li>
                  <NavLink to="/contact">Contact</NavLink>
                </li>
              </ul>
            </nav>
          </header>
          <section>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/news" element={<News />} />
              <Route path="/contact" element={<Contact />} />
              <Route path="*" element={<ErrorPage />} />
            </Routes>
          </section>
        </div>
      </Router>
    );
  }
}

export default App;

Why This Works

  • The path="*" acts as a catch-all route. It will only be rendered if none of the preceding routes match the current URL.
  • This tells React Router that you’ve explicitly handled all unmatched paths, so it won’t throw the "No routes matched location" warning anymore.
  • Your ErrorPage will now display correctly for any URL that isn’t /, /news, or /contact.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:34:06