表单重新提交
On this page

表单重新提交

¥Form Resubmissions

当你在 Remix 中使用 <Form method="post"> 时,与使用原生 HTML <form method="post"> 不同,Remix 不会遵循浏览器在导航事件(例如单击后退、前进或刷新)期间重新提交表单的默认行为。

¥When you use <Form method="post"> in Remix, as opposed to using the native HTML <form method="post">, Remix does not adhere to the default browser behavior for resubmitting forms during navigation events like clicking back, forward, or refreshing.

浏览器的默认行为

¥The Browser's Default Behavior

在标准浏览器环境中,表单提交属于导航事件。这意味着当用户点击后退按钮时,浏览器通常会重新提交表单。例如:

¥In a standard browser environment, form submissions are navigation events. This means that when a user clicks the back button, the browser will typically resubmit the form. For example:

  1. 用户访问 /buy

    ¥User visits /buy

  2. 将表单提交到 /checkout

    ¥Submits a form to /checkout

  3. 导航到 /order/123

    ¥Navigates to /order/123

浏览器历史记录堆栈如下所示:

¥The browser history stack would look like this:

GET /buy > POST /checkout > *GET /order/123

如果用户点击后退按钮,历史记录将变为:

¥If the user clicks the back button, the history becomes:

GET /buy - *POST /checkout < GET /order/123

在这种情况下,浏览器会重新提交表单数据,这可能会导致诸如重复扣款信用卡等问题。

¥In this situation, the browser resubmits the form data, which could lead to issues such as charging a credit card twice.

action 重定向

¥Redirecting from actions

避免此问题的常见做法是在 POST 请求后发出重定向。这会从浏览器历史记录中删除 POST 操作。历史记录堆栈将如下所示:

¥A common practice to avoid this issue is to issue a redirect after the POST request. This removes the POST action from the browser's history. The history stack would then look like this:

GET /buy > POST /checkout, Redirect > GET /order/123

使用这种方法,点击“后退”按钮不会重新提交表单:

¥With this approach, clicking the back button would not resubmit the form:

GET /buy - *GET /order/123

需要考虑的具体场景

¥Specific Scenarios to Consider

虽然 Remix 通常不会发生意外重新提交,但在某些特定情况下可能会发生。

¥While accidental resubmissions generally don't happen in Remix, there are specific scenarios where they might.

  • 你使用了 <form> 而不是 <Form>

    ¥You used <form> instead of <Form>

  • 你使用了 <Form reloadDocument>

    ¥You used <Form reloadDocument>

  • 你没有渲染 <Scripts/>

    ¥You are not rendering <Scripts/>

  • JavaScript 已被用户禁用。

    ¥JavaScript is disabled by the user

  • 提交表单时 JavaScript 尚未加载。

    ¥JavaScript had not loaded when the form was submitted

建议从操作中实现重定向,以避免意外的重新提交。

¥It's advisable to implement a redirect from the action to avoid unintended resubmissions.

其他资源

¥Additional Resources

指南

¥Guides

API

Remix v2.17 中文网 - 粤ICP备13048890号