next.js 如何正确调用创建的类型?

6kkfgxo0  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(83)

我创建了一个类型,这样我就可以在任何我想要的地方使用它,而不必调用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>
  );
};


提前感谢您的关注!!
我尝试了什么:打电话:

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: "[email protected],
imagePhoto: "<the photo in base64>"
}

更改第一个答案后出现新错误

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"] || '',

rhfm7lfc

rhfm7lfc1#

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组件中显示信息。
对于新错误!
你似乎遇到了一个名为“Invalid hook call”的错误。这个错误通常发生在试图在函数组件之外或在不允许hook的上下文中使用React hook(在本例中为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 };

配置文件.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函数。这确保了你遵循React钩子的规则,并应该解决“无效钩子调用”错误。

相关问题