我不明白为什么我的useEffect没有被调用?我现在正在听Youtube的教程,我所有的代码看起来都和视频中的一模一样。我读到了这篇文章:useEffect not being called and not updating state when api is fetched,但我无法将它与我的问题联系起来,所以我想知道是否有人能在这方面帮助我。
非常感谢。
import { useSession } from "next-auth/react";
import { ChevronDownIcon } from "@heroicons/react/outline";
import { useEffect, useState } from "react";
import { shuffle } from "lodash";
const colors = [
"from-indigo-500",
"from-blue-500",
"from-green-500",
"from-red-500",
"from-yellow-500",
"from-pink-500",
"from-purple-500",
];
function Center() {
const { data: session } = useSession();
const [color, setColor] = useState(null);
useEffect(() => {
console.log("useEffect called");
setColor(shuffle(colors).pop());
}, []);
return (
<div className="flex-grow">
<header className="absolute top-5 right-8">
<div className="flex items-center bg-red-300 space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2">
<img
className="rounded-full w-10 h-10"
src={session?.user.image}
alt=""
/>
<h2>{session?.user.name}</h2>
<ChevronDownIcon className="h-5 w-5" />
</div>
</header>
<section
className={
"flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
}
>
<h1>hello</h1>
</section>
</div>
);
}
export default Center;MRE:
import { useEffect, useState } from "react";
const colors = [
"from-indigo-500",
"from-blue-500",
"from-green-500",
"from-red-500",
"from-yellow-500",
"from-pink-500",
"from-purple-500",
];
function Center() {
const [color, setColor] = useState(null);
useEffect(() => {
console.log("useEffect called");
}, []);
return (
<div className="flex-grow">
<section
className={
"flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
}
>
</section>
</div>
);
}
export default Center;终于解决了!
${colors}应该是${color},className={}中的所有内容都需要被 not“包围”。我最初以为useEffect()甚至没有被调用,因为我看到的是VSCode终端而不是铬控制台。
发布于 2022-05-25 19:42:21
也许听起来很明显,但您确定没有从chrome developer工具中筛选出控制台日志吗?默认显示信息、警告和错误,但我经常过滤一个,下次打开控制台时必须重新设置它。
https://stackoverflow.com/questions/72382726
复制相似问题