簡體   English   中英

如何在 React Router V6 中顯示 404 錯誤頁面

[英]How to show 404 Error Page in React Router V6

我正在為我的 webapp 前端使用 React。 但是在開發過程中,我遇到了 react-router-dom V6 中的路由問題。 那個問題是如果沒有匹配的路由我想顯示 404 錯誤頁面。 這是我的代碼,

import React from 'react';
import { BrowserRouter,Routes,Route} from 'react-router-dom';
import Home from "./Pages/Home"
import Allposts from './Pages/Allposts'
import Createpost from './Pages/Createpost'
import Error404 from './Pages/Error404'

const App = () => {
    return(
        <>
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home />}/>
                <Route path="/all-posts" element={<Allposts />}/>
                <Route path="/create-post" element={<Createpost />} />
                <Route path="*" element={<Error404 />} />
            </Routes>
        </BrowserRouter>
        </>
    )
}

export default App;

如您所見,我在末尾添加了 catch all routes Route,路徑等於“*”標記。 這會捕獲除嵌套路由之外的所有路由(這就是問題所在)。 按照一般規則,它應該捕獲所有嵌套或未嵌套的路由,並且應該顯示 404 錯誤頁面組件。 當我使用路由“localhost:3000/all-posts/12345”時 <--- 因為這條路由不存在,所以它應該顯示 404 錯誤頁面組件而不是顯示它,它只顯示一個空白頁面並彈出一個錯誤控制台說找不到資源,錯誤為 404 就是這樣。

這就是問題。 如何解決這個問題並顯示 404 錯誤頁面組件。

嗨,你試過了嗎?

嘗試這個

<Switch>
   <Route path='*' component={Error404} />
</Switch>

如果帖子存在或不存在,反應無法自行檢查,您可以像這樣進行簡單檢查來處理它

 if (post exists) { return <Post/>; //render Post info/details } else { return <Error404 />; // if not redirect to 404 }

如果您可以切換到此方法,它也適用於所有嵌套組件。

import { createBrowserRouter, RouterProvider } from 'react-router-dom';

function Error404() {
  return <h2>404 Not found</h2>;
}

const router = createBrowserRouter([
  {
    path: '/',
    errorElement: <Error404 />,
    children: [
      {path: '', element: <Home /> },
      {path: 'all-posts', element: <Allposts /> },
      {path: 'create-post', element: <Createpost /> },
    ],
  },
]);

function Router() {
  return (
    <RouterProvider router={router} />
  );
}

export default Router;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM