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

如何使用React Router Dom在Slug不存在时实现无刷新跳转至NotFound页面

实现无效Slug的无刷新NotFound跳转

你遇到的问题很典型——window.location.href是浏览器原生的跳转方式,会触发页面重新加载,而React Router提供了客户端路由的导航API,能完美实现无刷新跳转需求。下面分两种主流React Router版本给出解决方案:

如果你使用的是React Router v5

React Router v5通过useHistory Hook来管理客户端导航:

  1. 首先导入useHistory:
import { useHistory } from 'react-router-dom';
  1. 在组件内部初始化history对象:
const history = useHistory();
  1. 把catch块里的window.location.href = "/not-found"替换为history.replace('/not-found'):
useEffect(() => {
  getSlug(slug)
    .then((res) => {
      const { id } = res.data;
      document.title = res.data.title;
      getSetting(id).then((result) => {
        setStyle(result.data);
        getLangue(id).then((res) => {
          setlang(res.data.langue);
        });
      });
    })
    .catch((error) => {
      // 用replace而非push,避免用户返回时回到无效slug页面
      history.replace('/not-found');
    });
}, [slug, history]);

这里选择replace而不是push的原因:push会在浏览器历史记录中新增一条记录,用户点击返回会回到之前的无效slug页面;replace则会替换当前历史记录,更符合错误页面的跳转逻辑。

如果你使用的是React Router v6

React Router v6重构了导航API,用useNavigate替代了useHistory:

  1. 导入useNavigate:
import { useNavigate } from 'react-router-dom';
  1. 初始化navigate函数:
const navigate = useNavigate();
  1. 在catch块中使用navigate方法,并传入replace: true选项:
useEffect(() => {
  getSlug(slug)
    .then((res) => {
      const { id } = res.data;
      document.title = res.data.title;
      getSetting(id).then((result) => {
        setStyle(result.data);
        getLangue(id).then((res) => {
          setlang(res.data.langue);
        });
      });
    })
    .catch((error) => {
      // replace: true 等价于v5的history.replace
      navigate('/not-found', { replace: true });
    });
}, [slug, navigate]);

方案生效的核心原因

React Router的导航方法是在客户端直接处理路由切换,不会向服务器发送新的HTTP请求,因此不会触发页面刷新。而window.location.href会强制浏览器重新请求目标URL,导致页面完全重载,这就是两者的核心差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:14:07