【问题标题】:react router dom v6 doesnt redirect to not found反应路由器dom v6没有重定向到未找到
【发布时间】:2021-12-29 20:34:21
【问题描述】:

所以我刚刚从 react-router-dom v5 迁移到 v6。

据我了解,exact 不再存在,因为它被省略了。但就我而言,它不起作用。

如果找不到路由,它应该重定向到not-found 页面,但不知道为什么它不起作用。它只是给我打印了一张白页......

所以,这是我的 BrowerRouter :

<BrowserRouter>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<AboutUs />} />
      <Route path="/contact" element={<Contact />} />
      <Route path="/publish-article" element={<WriteArticle />} />
      <Route path="/search-article" element={<Search />} />
      <Route path="/article/:id" element={<Article />} />
      <Route path="/quizz" element={<Quizz />} />
      <Route path="/login" element={<Login />} />
      <Route path="/register" element={<Register />} />
      <Route path="/profile/:username" element={<UserProfile />} />
      <Route path="/profile-settings" element={<ProfileSettings />} />
      <Route path="/not-found" element={<NotFound />} />
      <Route element={<NotFound />} />
    </Routes>
  </BrowserRouter>

有人知道我错过了什么吗?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    您仍然需要为未找到的 Route 设置路径,并将其作为通配符。

    <Route path="*" element={<NotFound />} />
    

    但是,如果您确实希望将 url 重定向到 not-found,那么只需在其中添加 Navigate 组件

    import { Navigate } from 'react-router-dom'
    
    <Route path="*" element={<Navigate to="not-found"/>} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2021-01-18
      • 2022-01-19
      相关资源
      最近更新 更多