我试图将从getSession获得的会话(使用next-auth)作为道具传递给页面。我知道我可以在组件中使用useSession(),但根据我的理解,这也应该是有效的,我不明白为什么它不起作用。
这似乎是一个类似的问题,在这个问题,但没有答案。
这是我最基本的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会话类型进行了如下扩展(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和NextJ的理解,上面的代码应该工作得完美无缺,但是当访问页面时,我会得到
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 | 我做错了什么?
发布于 2022-08-17 15:47:48
我也面临着同样的问题,并通过纯粹的运气解决了这个问题。
似乎Next.js通过其pageProps在页面中使用了session支柱。因此,当我们试图直接从session传递getServerSideProps时,由于某种原因,它在客户端组件上是没有定义的。
简而言之,只需从session返回用户,或者将会话变量重命名为其他内容。
这是我在所有需要SSR保护的应用程序中使用的patten:
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,
},
};
};发布于 2022-03-30 11:26:00
不过,正如前面提到的,如果会话中有用户对象,而用户对象中有id,则一切看起来都很好。所以,您可以使用可选的改变。
<Typography variant="h3">Settings</Typography>
<Typography>UserId: {user?.id}</Typography>发布于 2022-03-30 14:07:17
下一博士 interface {user: User & DefaultSession['user']}
https://stackoverflow.com/questions/71676115
复制相似问题