类型错误:无法读取未定义的属性(读取“用户”)
2022-02-05
4379
我正在尝试使用 Nextjs 创建一个 Facebook 克隆,并创建了 nextjsAuth 并配置了登录,现在我尝试将我的 Facebook 个人资料图片放入我的克隆中,并显示此错误,我尝试运行但显示此错误,我不知道该怎么办,有人可以解决这个问题吗,请
pages\components\Header.js (69:23) @ Header
67 | onClick={signOut}
68 | className="rounded-full cursour-pointer"
> 69 | src={session.user.image}
| ^
70 | width="40"
71 | height="40"
72 | layout="fixed"
full code is shown below you can checkout can you solve this error
import React from "react";
import Image from "next/image";
import {
BellIcon,
ChatIcon,
ChevronDownIcon,
HomeIcon,
UserGroupIcon,
ViewGridIcon,
} from "@heroicons/react/solid";
import {
FlagIcon,
PlayIcon,
SearchIcon,
ShoppingCartIcon,
} from "@heroicons/react/outline";
import HeaderIcon from "./HeaderIcon";
import { signOut, useSession } from "next-auth/react";
function Header() {
const {session} = useSession();
return (
<div
className="sticky top-0 z-50 bg-white
flex items-center p2
lg:px-5 shadow-md"
>
<div className="flex items-center">
{/* Left */}
<Image
alt="facebook"
src="https://links.papareact.com/5me"
width={40}
height={40}
layout="fixed"
/>
<div className="flex ml-2 item-center rounded-full bg-gray-100 p-2">
<SearchIcon className="h-6 text-gray-600" />
<input
className=" hidden md:inline-flex flex ml-2 items-center bg-transparent outline-none
placeholder-gray-502 flex-shrink"
type="text"
placeholder="Search Facebook"
/>
</div>
</div>
{/* Center */}
<div className="flex justify-center flex-grow">
<div className="flex space-x-6 md:space-x-2 ">
<HeaderIcon active Icon={HomeIcon} />
<HeaderIcon Icon={FlagIcon} />
<HeaderIcon Icon={PlayIcon} />
<HeaderIcon Icon={ShoppingCartIcon} />
<HeaderIcon Icon={UserGroupIcon} />
</div>
</div>
{/* Right */}
<div className="flex items-center sm:space-x-2 justify-end">
{/* Profile pic */}
<Image
onClick={signOut}
className="rounded-full cursour-pointer"
src={session.user.image}
width="40"
height="40"
layout="fixed"
/>
<p className="whitespace-nowrap font-semibold pr-3">Asram Ahamed</p>
<ViewGridIcon className="icon" />
<ChatIcon className="icon" />
<BellIcon className="icon" />
<ChevronDownIcon className="icon" />
</div>
</div>
);
};
export default Header;
3个回答
我用
const { data: session } = useSession();
修复了这个问题并且成功了
Azr.em
2022-02-07
刚刚解决了这个问题。您正在客户端获取会话,因此在获取客户端数据时会延迟 - 这会导致错误,因为在获取之前会话为“空”。
要解决此问题,请尝试使用以下示例在服务器端加载会话:
import { useSession, getSession } from 'next-auth/react'
const Example = () => {
const { data: session } = useSession();
console.log(session)
...
<div><Image src={session.user.image} /></div>
...
}
export async function getServerSideProps(context) {
return {
props: {
session: await getSession(context)
},
}
}
export default Example;
Beaumont
2022-05-19
变量
session
可能未定义。
请尝试按如下方式访问以解决此问题
<Image
onClick={signOut}
className="rounded-full cursour-pointer"
src={session?.user?.image}
width="40"
height="40"
layout="fixed"
/>
Dev-2019
2022-02-05