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

React Router最新版本中URL无效时重定向至首页的实现方法

React Router 最新版本实现404重定向至首页

你的现有路由代码:

<Routes>
    <Route path='/' element={<User/>} />
    <Route path='/:userId/places' exact element={<UserPlaces/>} />
    <Route path='/places/new' element={<NewPage/>}/>
    <Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
</Routes>

在React Router v6及以上版本中,<Redirect>组件已被移除,你可以通过以下两种方式实现未匹配路径重定向至首页:

方式一:直接使用Navigate组件匹配所有未定义路径

在路由列表的末尾添加一个通配符路由,使用path="*"匹配所有未被前面路由命中的路径,通过<Navigate>组件跳转至首页,replace属性可避免无效路径留存到浏览器历史记录中:

import { Routes, Route, Navigate } from 'react-router-dom';

// 导入你的组件(User、UserPlaces等)

<Routes>
  <Route path='/' element={<User/>} />
  <Route path='/:userId/places' element={<UserPlaces/>} />
  <Route path='/places/new' element={<NewPage/>}/>
  <Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
  {/* 404重定向路由 */}
  <Route path="*" element={<Navigate to="/" replace />} />
</Routes>

方式二:自定义404页面后延迟重定向

如果需要先展示自定义404提示页面,再跳转至首页,可借助useNavigate钩子实现:

import { useNavigate, useEffect } from 'react-router-dom';

// 自定义404组件
function NotFoundPage() {
  const navigate = useNavigate();

  useEffect(() => {
    // 设置2秒延迟后跳转,可根据需求调整时长
    const redirectTimer = setTimeout(() => {
      navigate('/', { replace: true });
    }, 2000);

    // 组件卸载时清除定时器
    return () => clearTimeout(redirectTimer);
  }, [navigate]);

  return <div>页面不存在,即将跳转到首页...</div>;
}

// 在路由中使用
<Routes>
  <Route path='/' element={<User/>} />
  <Route path='/:userId/places' element={<UserPlaces/>} />
  <Route path='/places/new' element={<NewPage/>}/>
  <Route path='/places/:placeId' element={<UpdatePlace/>}></Route>
  <Route path="*" element={<NotFoundPage />} />
</Routes>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:05:37