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

Next.js实现条件式返回按钮:无历史记录时跳转首页

解决方案

可以通过判断浏览器历史记录长度实现条件式返回逻辑:当存在可返回的历史记录时调用返回方法,否则重定向到首页。以下是不同场景的实现示例:

Vue Router(Vue 2/Vue 3)

在/message/:id页面的返回按钮点击事件中添加逻辑:

handleBack() {
  // 新打开页面的history.length初始为1,大于1则说明存在前置历史记录
  if (window.history.length > 1) {
    this.$router.back();
  } else {
    this.$router.push('/');
  }
}

React Router v6+

借助useNavigate钩子实现条件跳转:

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

function MessageDetail() {
  const navigate = useNavigate();

  const handleBack = () => {
    if (window.history.length > 1) {
      navigate(-1); // 等价于router.back()
    } else {
      navigate('/');
    }
  };

  return (
    <button onClick={handleBack}>返回</button>
  );
}

原生JS场景

不依赖路由框架时,直接操作浏览器History API:

function handleBack() {
  if (window.history.length > 1) {
    window.history.back();
  } else {
    window.location.href = '/';
  }
}

注意事项

  • 多数浏览器中,新打开页面的history.length初始值为1,以此作为判断依据可靠。
  • 若页面通过router.replace()跳转而来,历史记录会被替换,history.length不会增加,需根据业务场景调整判断逻辑。

内容的提问来源于stack exchange,提问作者Deep Shetye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:22:39