简体   繁体   English

刷新页面时 useEffect 不需要的副作用

[英]useEffect unwanted side effect when refresh page

In my account page, after logging in, I want to display dynamic ways of greeting plus the name of the user from the firebase users document.在我的帐户页面中,登录后,我想显示动态问候方式以及 firebase 用户文档中的用户名。 I use react typed for the greetings.我使用 react typed 作为问候语。

When I login, everything seems to work well;当我登录时,一切似乎都运行良好; but, when I refresh the page, all the content vanish and in console I get the following error message:但是,当我刷新页面时,所有内容都消失了,并且在控制台中我收到以下错误消息:

index.esm2017.js:1032 Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf'). index.esm2017.js:1032 未捕获类型错误:无法读取未定义的属性(读取“indexOf”)。

However, if I remove the user from dependencies array in useEffect , the error is gone but, in the console, I see how it loops infinitely.但是,如果我从useEffect中的 dependencies 数组中删除用户,错误就会消失,但在控制台中,我看到它是如何无限循环的。 I think this is because of react typed.我认为这是因为反应类型。

Can someone, please, tell me what am I doing wrong and explain how to use useEffect properly in this situation?有人可以告诉我我做错了什么并解释在这种情况下如何正确使用useEffect吗?

Here is the code:这是代码:

import React, { useState, useEffect } from "react";
import Typed from "react-typed";
import { UserAuth } from "../contexts/AuthContext";
import { db } from "../utils/firebase/firebase.utils";
import { doc, getDoc } from "firebase/firestore";

const Hero = () => {
  const [userDetails, setUserDetails] = useState({});
  const { user } = UserAuth();

  useEffect(() => {
    const docRef = doc(db, "users", user.uid);

    const fetchData = async () => {
      const docSnap = await getDoc(docRef);
      setUserDetails(docSnap.data());
      console.log(docSnap.data());
    };
    fetchData();
  }, [user]);

  return (
    <div className="text-white">
      <div className="max-w-[800px] mt-[-96px] w-full h-screen mx-auto text-center flex flex-col justify-center">
        <div className="flex justify-center items-center">
          <Typed
            className="md:text-5xl sm:text-4xl text-xl font-bold md:pl-4 pl-2"
            strings={["Hello,", "Hola,"]}
            typeSpeed={120}
            backSpeed={140}
            loop
          />
          <p className="md:text-5xl sm:text-4xl text-xl font-bold py-4">
            {userDetails.displayName}!
          </p>
        </div>
      </div>
    </div>
  );
};

export default Hero;

Likely the error is being caused because user or userDetails doesn't exist when your useEffect is run for the first time and user.uid is causing the error.可能会导致错误,因为第一次运行useEffect时 user 或 userDetails 不存在,而user.uid导致错误。

Can do something like this to solve the issue可以做这样的事情来解决问题

useEffect(() => {
    if (!user) return;

    const docRef = doc(db, "users", user.uid);

    const fetchData = async () => {
      const docSnap = await getDoc(docRef);
      setUserDetails(docSnap.data());
      console.log(docSnap.data());
    };
    fetchData();
  }, [user]);

if (!user && userDetails === {}) {
  return <div>Loading.</div<
}

Though the UserAuth() hook might have a loading property that it returns that can be used instead for a better way of doing this.尽管 UserAuth() 挂钩可能有一个它返回的加载属性,但可以使用它来更好地执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM