首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么useEffect不被调用?

为什么useEffect不被调用?
EN

Stack Overflow用户
提问于 2022-05-25 18:42:08
回答 1查看 79关注 0票数 1

我不明白为什么我的useEffect没有被调用?我现在正在听Youtube的教程,我所有的代码看起来都和视频中的一模一样。我读到了这篇文章:useEffect not being called and not updating state when api is fetched,但我无法将它与我的问题联系起来,所以我想知道是否有人能在这方面帮助我。

非常感谢。

代码语言:javascript
复制
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:

代码语言:javascript
复制
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终端而不是铬控制台。

EN

回答 1

Stack Overflow用户

发布于 2022-05-25 19:42:21

也许听起来很明显,但您确定没有从chrome developer工具中筛选出控制台日志吗?默认显示信息、警告和错误,但我经常过滤一个,下次打开控制台时必须重新设置它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72382726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档