使用fetch调用Remix Action函数时能否实现页面重定向?
使用Fetch调用Remix Action时实现页面重定向的方法
你遇到的情况是:用原生fetch调用Remix Action,Action返回redirect后,网络面板能看到重定向的GET请求,但页面并未跳转。这是因为原生fetch默认只会自动跟随重定向获取响应内容,不会触发浏览器的页面跳转,需要手动处理或改用Remix原生工具。
以下是三种可行解决方案:
解决方案1:手动处理Fetch响应的重定向
通过配置fetch的redirect: "manual"阻止自动跟随,读取响应头的Location字段手动触发跳转:
const Component = () => { useEffect(() => { const timer = setTimeout(async () => { const data = { redirectTo: "/home" }; const res = await fetch("test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, redirect: "manual", // 禁用自动跟随重定向 }); const redirectUrl = res.headers.get("Location"); if (redirectUrl) { window.location.href = redirectUrl; } }, 2500); return () => clearTimeout(timer); }, []); return <div>...</div>; };
解决方案2:Action返回JSON,前端主动跳转
修改Action返回包含跳转地址的JSON,前端拿到结果后手动跳转:
// Action 部分 export const action: ActionFunction = async ({ request }) => { const data = await request.json(); return json({ redirectTo: data.redirectTo }); }; // Component 部分 const Component = () => { useEffect(() => { const timer = setTimeout(async () => { const data = { redirectTo: "/home" }; const res = await fetch("test", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); const result = await res.json(); window.location.href = result.redirectTo; }, 2500); return () => clearTimeout(timer); }, []); return <div>...</div>; };
解决方案3:使用Remix的useFetcher钩子(推荐)
Remix提供的useFetcher会自动处理Action返回的重定向,更符合框架设计逻辑:
import { useFetcher } from "@remix-run/react"; const Component = () => { const fetcher = useFetcher(); useEffect(() => { const timer = setTimeout(() => { fetcher.submit( { redirectTo: "/home" }, { method: "post", action: "/test", headers: { "Content-Type": "application/json" } } ); }, 2500); return () => clearTimeout(timer); }, [fetcher]); return <div>...</div>; };
内容的提问来源于stack exchange,提问作者nadiTime
相关产品推荐
相关产品推荐

