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

如何在react-router-dom v6的页面action()处理器中跳转回上一页?

React Router 6.11.2 中表单提交后返回上一页的正确处理方式

问题原因

redirect('..') 是基于当前路由层级的相对跳转,并非浏览器历史记录中的“上一页”。比如当前路由为 /posts/1/edit,.. 会跳转到 /posts/1;如果用户直接访问 /posts/1/edit(而非从其他页面导航过来),.. 会跳转到 /posts,而非用户期望的来源页。

官方推荐的两种解决方案

方案一:通过表单传递来源页路径(更可控)

  1. 在导航到表单页时,将来源路径存入路由 state:
// 从列表页跳转到编辑页的示例
import { Link, useLocation } from 'react-router-dom';

function PostList() {
  const location = useLocation();
  return (
    <Link to="/posts/1/edit" state={{ from: location.pathname }}>
      编辑文章
    </Link>
  );
}
  1. 在表单组件中,将来源路径作为隐藏字段提交:
import { useLocation, Form } from 'react-router-dom';

function EditPostForm() {
  const location = useLocation();
  // 若没有来源页,默认跳转到主页
  const from = location.state?.from || '/';

  return (
    <Form method="post">
      {/* 其他表单字段 */}
      <input type="hidden" name="from" value={from} />
      <button type="submit">保存</button>
    </Form>
  );
}
  1. 在 action 函数中读取该字段并跳转:
export async function action({ request }) {
  const formData = await request.formData();
  const updates = Object.fromEntries(formData);
  const from = formData.get('from') || '/';

  // 调用API保存数据逻辑...

  return redirect(from);
}

方案二:利用请求头的 Referer(简单但依赖浏览器)

直接从请求头中获取上一页的 URL,作为跳转目标,同时处理 Referer 不存在的情况:

export async function action({ request }) {
  const formData = await request.formData();
  const updates = Object.fromEntries(formData);

  // 调用API保存数据逻辑...

  // 从请求头获取来源页,不存在则默认跳转到主页
  const referer = request.headers.get('Referer') || '/';
  return redirect(referer);
}

注意:部分浏览器或隐私设置会屏蔽 Referer 头,这种情况下会 fallback 到主页,因此方案一更稳定可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:38:32