gpt4 book ai didi

reactjs - Next-auth:尽管从 getServerSideProps 传递到页面的 Prop 未定义

转载 作者:行者123 更新时间:2023-12-05 03:26:43 29 4
gpt4 key购买 nike

我正在尝试将从getSession(使用next-auth)获取的 session 作为 Prop 传递给页面。我知道我可以在组件内使用 useSession(),但据我所知,这应该也能正常工作,但我不明白为什么不行。

这似乎与 this question 中的问题类似但没有答案。

这是我非常基本的 pages/settings.tsx:

import { Card, CardContent, Typography } from "@mui/material";
import { User } from "@prisma/client";
import { GetServerSideProps, NextPage } from "next";
import { getSession } from "next-auth/react";

interface SettingsProps {
user: User,
}

const Settings : NextPage<SettingsProps> = ({user})=>{
// in here, user is always undefined...
return (
<Card>
<CardContent>
<Typography variant="h3">Settings</Typography>
<Typography>UserId: {user.id}</Typography>
<Typography>Created: {(new Date(user.createdAt)).toLocaleDateString()}</Typography>
</CardContent>

</Card>
);
};

export const getServerSideProps: GetServerSideProps<SettingsProps> = async (context) =>{
const session = await getSession(context);

if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}

console.log(session.user); // this works and logs the user

return {
props: { user: session.user },
};
};

export default Settings;

我已经像这样增强了 next-auth session 类型 (types/next-auth.d.ts):

import { User } from "@prisma/client";
import NextAuth from "next-auth";

declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: User
}
}

根据我对 React 和 NextJs 的理解,上面的代码应该可以完美运行,但是在访问页面时我得到了

TypeError: Cannot read properties of undefined (reading 'id')
13 | <CardContent>
14 | <Typography variant="h3">Settings</Typography>
> 15 | <Typography>UserId: {user.id}</Typography>
| ^
16 | <Typography>Created: {(new Date(user.createdAt)).toLocaleDateString()}</Typography>
17 | </CardContent>
18 |

我做错了什么?

最佳答案

我遇到了同样的问题,运气好就解决了。

Next.js 似乎通过其 pageProps 在页面中使用了 session 属性。因此,当我们尝试直接从 getServerSideProps 传递 session 时,由于某些原因,它在客户端组件上是未定义的。

简而言之,只需从 session 返回用户,或者将 session 变量重命名为其他名称即可。

这是我在整个应用程序中需要 SSR 身份验证保护的地方使用的模式:

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
const session = await unstable_getServerSession(req, res, authOptions);
const user = session?.user;

if (!user) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}

return {
props: {
user,
},
};
};

关于reactjs - Next-auth:尽管从 getServerSideProps 传递到页面的 Prop 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71676115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com