[英]How to solve React Hook useEffect has missing dependencies error?
How can I solve the Line 31:6: React Hook useEffect has missing dependencies: 'fetchUserName' and 'history'.如何解决第31:6 行:React Hook useEffect 缺少依赖项:“fetchUserName”和“history”。 Either include them or remove the dependency array react-hooks/exhaustive-deps ?
包括它们或删除依赖数组 react-hooks/exhaustive-deps ? I am not able to solve it.
我无法解决它。 I am using Firebase for authentication.
我正在使用 Firebase 进行身份验证。 Please help me!!!!!
请帮我!!!!!
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;
Normally it should be fine to add 'fetchUserName' and 'history' to the array at the end of useEffect:通常,在 useEffect 的末尾将 'fetchUserName' 和 'history' 添加到数组中应该没问题:
useEffect(() => {
if (loading) return;
if (!user) return history.replace("/");
fetchUserName();
}, [
user,
loading,
fetchUserName,
history
]);
React functional component uses closures. React 功能组件使用闭包。
when state updates not all functions know the updated value, they only know the initialized value当 state 更新时,并非所有函数都知道更新后的值,它们只知道初始化值
when you are using useEffect
you need to make sure that useEffect hook knows the updated values, even more, the functions that the useEffect invokes also need to know the updated values so if you have a warning that says you missing some dependencies, you probably need to listen to it当您使用
useEffect
时,您需要确保 useEffect 钩子知道更新的值,甚至更多,useEffect 调用的函数也需要知道更新的值,因此如果您收到警告说您缺少某些依赖项,您可能需要听它
If you really don't need it and you want to remove the warning you can put this right before the end of the useEffect/ useCallback如果你真的不需要它并且你想删除警告你可以把它放在useEffect/ useCallback 结束之前
// eslint-disable-next-line react-hooks/exhaustive-deps
But again they didn't send this by mistake, there are reasons why they send it and a good ones但是他们又一次没有错误地发送这个,他们发送它是有原因的,而且是好的
you could use this你可以用这个
useEffect(() => {
if (loading) return;
if (!user) return history.replace("/");
fetchUserName();
// eslint-disable-next-line
}, [user, loading]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.