繁体   English   中英

如何解决 React Hook useEffect has missing dependencies 错误?

[英]How to solve React Hook useEffect has missing dependencies error?

如何解决第31:6 行:React Hook useEffect 缺少依赖项:“fetchUserName”和“history”。 包括它们或删除依赖数组 react-hooks/exhaustive-deps 我无法解决它。 我正在使用 Firebase 进行身份验证。 请帮我!!!!!

import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useHistory } from "react-router";
import "./Dashboard.css";
import { auth, db, logout } from "./firebase";

function Dashboard() {
  const [user, loading] = useAuthState(auth);
  const [name, setName] = useState("");
  const history = useHistory();

  const fetchUserName = async () => {
    try {
      const query = await db
        .collection("users")
        .where("uid", "==", user?.uid)
        .get();
      const data = await query.docs[0].data();
      setName(data.name);
    } catch (err) {
      console.error(err);
      alert("An error occured while fetching user data");
    }
  };

  useEffect(() => {
    if (loading) return;
    if (!user) return history.replace("/");

    fetchUserName();
  }, [user, loading]);

  return (
    <div className="dashboard">
      <div className="dashboard__container">
        Logged in as
        <div>{name}</div>
        <div>{user?.email}</div>
        <button className="dashboard__btn" onClick={logout}>
          Logout
        </button>
      </div>
    </div>
  );
}

export default Dashboard;

通常,在 useEffect 的末尾将 'fetchUserName' 和 'history' 添加到数组中应该没问题:

useEffect(() => {
  if (loading) return;
  if (!user) return history.replace("/");

  fetchUserName();
}, [
  user, 
  loading,
  fetchUserName,
  history
]);

React 功能组件使用闭包。
当 state 更新时,并非所有函数都知道更新后的值,它们只知道初始化值

当您使用useEffect时,您需要确保 useEffect 钩子知道更新的值,甚至更多,useEffect 调用的函数也需要知道更新的值,因此如果您收到警告说您缺少某些依赖项,您可能需要听它

如果你真的不需要它并且你想删除警告你可以把它放在useEffect/ useCallback 结束之前

        // eslint-disable-next-line react-hooks/exhaustive-deps

但是他们又一次没有错误地发送这个,他们发送它是有原因的,而且是好的

你可以用这个

useEffect(() => {
    if (loading) return;
    if (!user) return history.replace("/");

    fetchUserName();
    // eslint-disable-next-line
  }, [user, loading]);

暂无
暂无

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

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