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

React Router DOM Form组件首页提交错误时URL追加/?index问题排查

问题原因与解决方案

问题原因

URL后追加/?index是React Router处理根索引路由表单提交的默认行为。当根路由(/)的action返回非重定向响应时,React Router会自动添加?index参数标识这是索引路由的action响应,其他非索引路由不存在该逻辑。

修复方案

修改Login组件中Form的action属性,从"."改为"/":

<Form
  action="/"
  method="post"
  noValidate
  className="mt-6 flex flex-col gap-5"
>

修改后,表单直接提交到根路由action,地址栏将保持localhost:5173/不变,同时useActionData仍可正常读取错误信息,不影响原有验证逻辑。


原问题相关代码参考

原Login组件的Form片段

// 原代码(存在问题的部分)
<Form
  action="."
  method="post"
  noValidate
  className="mt-6 flex flex-col gap-5"
>

原loginAction代码

import { LoaderFunctionArgs, redirect } from "react-router-dom";

interface Errors {
  email?: string;
  password?: string;
}

export default async function loginAction({ request }: LoaderFunctionArgs) {
  const formData = await request.formData();

  const email = formData.get("email") as string;
  const password = formData.get("password") as string;
  const errors: Errors = {};

  if (email === "") {
    errors.email = "Please enter your email";
  } else if (!email?.includes("@")) {
    errors.email = "Not a valid email";
  }

  if (password === "") {
    errors.password = "Please enter your password";
  } else if (password?.length < 8) {
    errors.password = "Password must be > 7 characters";
  }

  if (Object.keys(errors).length) {
    return errors;
  }

  return redirect("/dashboard");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:47:03