从API获取数据并重定向不起作用-NEXTJS



我正试图从API获取一些数据,并基于此响应重定向到页面。

应用程序流为:

用户单击按钮-->按钮调用函数-->函数从API获取数据,并根据获取的数据重定向到新的URL。

components/Start.js

import { setCookie } from "nookies";
export default function Start() {
return (
<button className="text-2xl font-bold" onClick={CreateAPI}>
Start &rarr;
</button>
);
}
async function CreateAPI() {
const res = await fetch(`https://**********/create`);
const data = await res.json();
if (!data) {
return {
redirect: {
destination: "/maintenance",
permanent: false,
},
};
}
console.log(data);
setCookie(null, "owner", "true", {
maxAge: 3600,
path: "/",
});
return {
redirect: {
destination: `/${data}`,
permanent: false,
},
};
}

index.js

import Head from 'next/head'
import Start from '../components/Start'

export default function Home() {
return (
<div className="flex flex-col items-center justify-center min-h-screen py-2">
<Head>
<title>xxx</title>
</Head>
<main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
<h1 className="text-6xl font-bold">
Welcome
</h1>

<div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
<a
className="p-6 mt-6 text-center border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
>
<Start />
</a>
</div>
</main>

当我点击按钮时,我可以在控制台上看到数据,但重定向没有发生。

如果你能指出正确的方向,那将是非常有帮助的。

感谢

CreateAPI函数只是返回一个如下所示的对象:

{
redirect: {
...
}
}

它实际上并没有在任何地方执行重定向。根据您使用的路由器类型,您可以调用适当的方法。如果您使用的是类似react-router的东西,则可以使用useNavigate挂钩(文档:https://reactrouter.com/docs/en/v6/api#usenavigate)

最新更新