我创建了一个类型,这样我就可以在任何地方使用它,而不必调用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"] || '',

推荐答案

在您的Profile组件中,您没有调用getUser函数.您只是将函数本身赋值给user变量.更新它以调用该函数,如下所示:

import { getUser } from "../../../@types/UserType";
import { ClientImage } from "../../../components/ClientImage";
import DevComponent from "../../../components/DevComponents";

export default function Profile() {
  const user = getUser(); // Call the function
  console.log("usuario:", user);
  
  if (user) {
    return (
      <div>
        <h1>Profile Page</h1>
        <p>Name: {user.name}</p>
        <p>Email: {user.email}</p>
        <p>Image Profile: {user.imageProfile}</p>
        <ClientImage />
        <DevComponent />
      </div>
    );
  } else {
    return <p>Loading...</p>; // Handle the case when user is not available yet
  }
}

在您的getUser函数中,您试图从UserType接口中构造属性,但该函数不接受任何参数.相反,您应该从函数中删除参数,并直接返回User对象:

"use client"
import { useSession } from "next-auth/react";

interface UserType {
  name: string;
  email: string;
  imageProfile: string;
}

const getUser = (): UserType | null => {
  const { data: session } = useSession();
  if (session) {
    return {
      name: session.user?.name || "",
      email: session.user?.email || "",
      imageProfile: session.user?.jpegPhoto || ""
    };
  }
  return null;
};

export { getUser };

确保使用空合并运算符(||)或可选链接(?.)处理属性可能为undefined的情况.

通过这些更改,您应该能够获取User对象并在您的Profile组件中显示信息.

For New Error!

看起来您正面临一个名为"无效的钩子调用"的错误.当试图在功能组件外部或在不允许挂钩的上下文中使用react 挂钩(在本例中为useSession)时,通常会出现此错误.

要解决此问题,

UserType.ts:

// UserType.ts
import { useSession } from "next-auth/react";

interface UserType {
  name: string;
  email: string;
  imageProfile: string;
}

const getUser = (): UserType | null => {
  const { data: session } = useSession();
  if (session) {
    return {
      name: session.user?.name || "",
      email: session.user?.email || "",
      imageProfile: session.user?.jpegPhoto || ""
    };
  }
  return null;
};

export { getUser };

Profile.tsx:

// Profile.tsx
import { ClientImage } from "../../../components/ClientImage";
import DevComponent from "../../../components/DevComponents";
import { useSession } from "next-auth/react";
import { getUser } from "../../../@types/UserType";

export default function Profile() {
  const { data: session } = useSession();
  const user = getUser(session);

  if (user) {
    return (
      <div>
        <h1>Profile Page</h1>
        <p>Name: {user.name}</p>
        <p>Email: {user.email}</p>
        <p>Image Profile: {user.imageProfile}</p>
        <ClientImage />
        <DevComponent />
      </div>
    );
  } else {
    return <p>Loading...</p>;
  }
}

为了修复这个错误,我将useSession挂钩移到了Profile.tsx组件中允许的位置,并将会话数据传递给了getUser函数.这可确保您遵循Reaction挂钩的规则,并应解决"无效挂钩调用"错误.

Typescript相关问答推荐

VS代码1.88.0中未出现自动导入建议

数组文字中对象的从键开始枚举

在分配给类型的只读变量中维护const的类型

带下拉菜单的Angular 响应式选项卡

有没有办法防止类型交集绕过联合类型限制?

为什么&Quot;元素隐式具有';Any';类型,因为...即使我已经打字了,也不能作为索引显示错误吗?

从类型脚本中元组的尾部获取第n个类型

如何键入派生类的实例方法,以便它调用另一个实例方法?

KeyOf关键字在特定示例中是如何工作的

如何以类型安全的方式指定键的常量列表,并从该列表派生所挑选的接口?

为什么`map()`返回类型不能维护与输入相同数量的值?

替换typescript错误;X类型的表达式可以';t用于索引类型Y;带有未定义

两个子组件共享控制权

如何向我的自定义样式组件声明 custom.d.ts ?

Next 13 + React 18 createContext 类型的构建问题

TS 排除带点符号的键

在Typescript 无法正常工作的 Three.js 中更新动画中的 GLSL 统一变量

如何使用动态生成的键和值定义对象的形状?

如何在 ngFor 循环中以Angular 正确动态渲染组件

如何为对象创建类型,其中键是只读且动态的,但值是固定类型?