如何在使用react-router-dom v6时,从页面的action()处理程序中重定向到上一页?

huangapple go评论58阅读模式
英文:

How to redirect to previous page using react-router-dom v6 from a page action() handler?

问题

I am using react-router-dom@6.11.2 and have several pages. User navigates from one page to another. The second page contains a pure functional form component that has both a react-router loader() and a submission action(). User fills out the form, clicks save, the action() function is called which saves the data to API, and then returns redirect("..") to navigate back to the previous page, but what React Router does is navigate back to the main page "/ instead.

In their API documentation on redirect() it does not say how to navigate back, only forwards:

https://reactrouter.com/en/main/fetch/redirect

Here is a simplified version of my form's action() function.

/** submit POST for add/update */
export async function action({ request, params }) {
   const formData = await request.formData();
   const updates = Object.fromEntries(formData);

   // call API, blah blah

   return redirect("..");
}

What is the official way to handle this?

英文:

I am using react-router-dom@6.11.2 and have several pages. User navigates from one page to another. The second page contains a pure functional form component that has both a react-router loader() and a submission action(). User fills out the form, clicks save, the action() function is called which saves the data to API, and then returns redirect("..") to navigate back to the previous page, but what React Router does is navigate back to the main page "/" instead.

In their API documentation on redirect() it does not say how to navigate back, only forwards:

https://reactrouter.com/en/main/fetch/redirect

Here is a simplified version of my form's action() function.

    /** submit POST for add/update */
    export async function action({ request, params }) {
       const formData = await request.formData();
       const updates = Object.fromEntries(formData);
    
       // call API, blah blah
    
       return redirect("..");
    }

What is the official way to handle this?

答案1

得分: 0

我为您创建了一段代码片段,希望对您有所帮助!

export async function action({ request }) {
  // 从表单获取数据。
  const formData = await request.formData();
  const email = formData.get("email");
  const password = formData.get("password");

  try {
    const logInResponse = await loginUser({ email, password }); // 您的API。
    return logInResponse; // 发送响应。
  } catch (error) {
    return {
      error: error.message,
    };
  }
}

export default function Login() {
  const location = useLocation(); // 捕获引用页面。
  const navigate = useNavigate(); // 重定向到页面。
  const actionData = useActionData(); // 捕获操作函数。

  const userFrom = location.state?.from || "/";

  React.useEffect(() => {
    if (actionData?.accessToken) {
      navigate(userFrom, {
        replace: true,
      });
    }
  }, [actionData]); // 如果操作函数起作用。

  return (<h1>登录页面</h1>);
}

如果您对它的工作原理感到好奇,您可以查看这个存储库

英文:

I created a code snippet for you, Hope it helps!

export async function action({ request }) {
  // Get data from the form.
  const formData = await request.formData();
  const email = formData.get(&quot;email&quot;);
  const password = formData.get(&quot;password&quot;);

  try {
    const logInResponse = await loginUser({ email, password }); // Your API.
    return logInResponse; // send a response.
  } catch (error) {
    return {
      error: error.message,
    };
  }
}

export default function Login() {
  const location = useLocation(); // Catch ref page.
  const navigate = useNavigate(); // Redirect to page.
  const actionData = useActionData(); // Catch action function.

  const userFrom = location.state?.from || &quot;/&quot;;

  React.useEffect(() =&gt; {
    if (actionData?.accessToken) {
      navigate(userFrom, {
        replace: true,
      });
    }
  }, [actionData]); // If the action function works.

  return (&lt;h1&gt;LoginPage&lt;/h1&gt;);
}

If you're curious about how it works, you can take a look at this repository.

huangapple
  • 本文由 发表于 2023年6月6日 04:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定