Remix React 返回 json 并重定向

问题描述 投票:0回答:2

在 Remix 中,如何在成功调用 API 后先返回

json
,然后返回
redirect

export const action: ActionFunction = async ({
    request,
}: ActionFunctionArgs) => {
    const formData = await request.formData();

    try {
        const { project } = await sampleAPICall(formData);
        return json({
            title: "Success",
            message: "Yehey!",
        });

        throw redirect(`/${project?.id}`); 
    } catch (error) {
        return json({
            variant: "destructive",
            message: "Oh no....",
        });
    }
};
javascript reactjs remix.run
2个回答
0
投票

我认为您需要构建代码来独立于 JSON 响应来处理重定向。您不能拥有在 return 语句之后执行的代码。

export const action: ActionFunction = async ({
    request,
    redirect,
}: ActionFunctionArgs) => {
    const formData = await request.formData();

    try {
        const { project } = await sampleAPICall(formData);
        return json({
            title: "Success",
            message: "Yehey!",
            redirectTo: `/${project?.id}`, // Include redirection URL in JSON response
        });
    } catch (error) {
        return json({
            variant: "destructive",
            message: "Oh no....",
        });
    }
};

export const loader: LoaderFunction = ({ json }) => {
    return json();
};

希望我能提供帮助!祝你好运! :)


0
投票

重定向不能有正文,因此您不能在重定向中包含 JSON 有效负载。如果您想在重定向的路线上显示消息,通常会使用会话闪存。

https://remix.run/docs/en/main/utils/sessions#sessionflashkey-value

import { commitSession, getSession } from "../sessions";

export async function action({
  params,
  request,
}: ActionFunctionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const formData = await request.formData;
  const { project } = await sampleAPICall(formData);
  session.flash("message", { title: "Success", message: "Yehey!" });

  return redirect("`/${project?.id}`, {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });
}

然后在你的项目路径中,你可以显示来自flash的消息

import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { getSession, commitSession } from "./sessions";

export async function loader({ request } LoaderFunctionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const message = session.get("message") || null;

  return json(
    { message },
    {
      headers: {
        // only necessary with cookieSessionStorage
        "Set-Cookie": await commitSession(session),
      },
    }
  );
}

export default function Component() {
  const { message } = useLoaderData<typeof loader>();

  return (
    <div>
      {message ? (
        <div className="flash">{message.title} {message.message}</div>
      ) : null}
    </div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.