我创建了一个类型,这样我就可以在任何地方使用它,而不必调用useSession(),因为它需要是一个客户端组件.但当我调用它时,它总是未定义(如果我调用特定属性)或空对象(如果我全部调用)
创建的类型:
"use client"
import { useSession } from "next-auth/react"
interface UserType {
name: string,
email: string,
imageProfile: string,
}
const getUser = (): UserType => {
const { data: session } = useSession()
if (session) {
return {
name: session.user["name"],
email: session.user["email"],
imageProfile: session.user["jpegPhoto"]
}
}
return null
};
export { getUser }
我要打给哪里:
import { getUser } from "../../../@types/UserType";
import { ClientImage } from "../../../components/ClientImage";
import DevComponent from "../../../components/DevComponents";
export default function Profile() {
const user = getUser
console.log("usuario:", user)
return (
<div>
<h1>Profile Page</h1>
<ClientImage />
<DevComponent />
</div>
);
};
提前感谢您的关注!!
我做了什么try : 来电:
const user = getUser()
console.log("usuario:", user.name)
const user = getUser
console.log("usuario:", user)
正在创建组件:
"use client"
import { useSession } from "next-auth/react"
interface UserType {
name: string,
email: string,
imageProfile: string,
}
const getUser = ({name,email, imageProfile}: UserType) => {
const { data: session } = useSession()
if (session) {
return {
name: session?.user["name"],
email: session?.user["email"],
imageProfile: session?.user["jpegPhoto"]
}
}
return null
};
export { getUser }
我等你回来的是什么:
user{
name: "sam",
email: "sam@domin.com,
imagePhoto: "<the photo in base64>"
}
New error after changes to the first answer个
Unhandled Runtime Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Source
src/types/UserType.ts (11:38) @ useSession
9 |
10 | function getUser(): UserType | null {
> 11 | const { data: session } = useSession()
| ^
12 | if (session) {
13 | return {
14 | name: session?.user["name"] || '',