我正在尝试将数据获取到 SSR 中的仪表板组件,但未定义
有什么解决方案可以正确获取数据吗?
这是我的仪表板组件代码:
import Container from "./Container";
import { getServerSession } from "next-auth/next";
import { authConfig } from "../../lib/auth";
import { getServer } from "@/app/api/servers";
export const getServerSideProps = async () => {
const session = await getServerSession(authConfig); // Wrap in getServerSession
const userId = session?.user.id;
const serverData = await getServer(userId); // Pass userId if needed
return { props: { serverData } }; // Return object with serverData prop
};
const Dashboard = ({ serverData }) => {
return (
<div className="w-full min-h-full p-4 border-b-2 border-t-2 border-t-white border-b-cyan-100 shadow-lg mb-8 h-80 min-h-72">
<div className="w-full h-full flex flex-row gap-5">
<Container serverData={serverdata} />
</div>
</div>
);
};
export default Dashboard;
这是我的 getServer 函数的代码:
export const getServer = async (userId: string) => {
console.log("getServer", userId);
try {
// Find servers belonging to the user
const servers = await prisma.server.findMany({
where: {
userId: userId,
},
});
return servers;
} catch (error) {
// Handle any errors
console.error("Error retrieving servers:", error);
throw error; // Re-throw the error for the caller to handle
}
};
只需创建异步函数来获取数据并在页面中调用它。
...
const getData = async ()=> {
return await getFromDb();
}
const Dashboard = async () =>{
const data = await getFromDb();
return (<>{data.id}<>);
}
Next +13 不支持旧版本的 getServerSideProps 。
如果您在组件或页面中没有使用像 useState 这样的钩子,您可以使用服务器组件来获取数据,如下所示:
"use server" // must be added at the top of the file
const Component = async ({ id }) => {
const data = await getData(id);
return <div>{data.name}</div>;
};