简体   繁体   中英

React Router V6 - NotFound component not working with dynamic parameter/slug?

I have installed "react-router-dom": "^6.0.0-beta.0" and created some page routes. Facing problems where the Page404 / NotFound component is not working if a page doesn't exist. For some reason when I am using dynamic page/post slug the component NotFound will not work if there is no page/post with this ID.

Is there an option inside React Router which solves this issue?

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

import AllPosts from "components/AllPosts";
import SinglePost from "components/SinglePost";
import NotFound from "components/Page404";

const App = () => (
  <Router>
    <Routes>
      <Route element={<AllPosts />} path="/" exact />
      <Route element={<SinglePost />} path="/:slug" />
      <Route element={<NotFound />} path="*" />
    </Routes>
  </Router>
);

export default App;

The Routes and Route component can't possibly know ahead of time that some dynamic path, "/someUnsupportedIdValue" for example, isn't a valid path to be handled by SinglePost .

The options you have here are:

  1. Conditionally render some alternative UI in SinglePost , something along the lines of "A page by this ID isn't found".
  2. Check if a page with matching ID exists, conditionally render that page, or a redirect ( Navigate component replaced Redirect in v6) to your more generic 404 page (actually, a redirect to any "throw away" path that isn't explicitly handled already will land you on your 404 page). Or you can imperatively redirect with a navigate(to, { replace: true }) .
  1. Try to remove exact because was removed from v6 and make sure Page404 is the correct component or create Notfound.jsx

  2. Check if the post not exists then redirect to Notfound page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM