内部使用效果导致无限循环
我想将列表使用到sedata
和setuserdata
。我正在使用数据通过用户列表映射并在表上显示。我正在使用userData
在不同组件中获取用户信息。这会导致无限循环。
import { useState, useEffect, useContext } from 'react';
import { collection, onSnapshot } from 'firebase/firestore';
import { db, auth } from '../../firebase';
import { UserContext } from '../../Contexts/UserContext';
const Datatable = () => {
const {userData, setUserData} = useContext(UserContext);
const [data, setData] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [currentId, setCurrentId] = useState("");
useEffect(() => {
const getUserData = () => {
onSnapshot(collection(db, "users"), (snapshot) => {
let list = [];
snapshot.docs.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() });
setData(list);
setUserData(list)
});
}, (err) => {
console.log(err);
});
}
getUserData();
}, [])
}
I want to use the list to seData
and setUserData
. I am using data to map through the list of users and display on the table. I am using the userData
to get user information in different components. This is causing infinite loop.
import { useState, useEffect, useContext } from 'react';
import { collection, onSnapshot } from 'firebase/firestore';
import { db, auth } from '../../firebase';
import { UserContext } from '../../Contexts/UserContext';
const Datatable = () => {
const {userData, setUserData} = useContext(UserContext);
const [data, setData] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [currentId, setCurrentId] = useState("");
useEffect(() => {
const getUserData = () => {
onSnapshot(collection(db, "users"), (snapshot) => {
let list = [];
snapshot.docs.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() });
setData(list);
setUserData(list)
});
}, (err) => {
console.log(err);
});
}
getUserData();
}, [])
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在使用效率下不应完成对状态的更新值。您必须在外部创建功能并更新状态值。
如果这样做,您将获得
警告:超过最大更新深度。
错误。发生这种情况,因为一旦您更新状态,状态的引用将被更改,并且会发生组件rerender。再次由于引用已更改。使用效应将再次调用,这无限地发生在一定程度之后的反应停止。
Updating values to the state should not be done in useEffect. You have to create a function outside and update the state value.
If you do so, You will be getting
Warning: Maximum update depth exceeded.
error.This happens because once if you update a state the reference of the state will be changed and component rerender happens. Again since the reference is changed. The useEffect will be called again and this happens infinitely which the react stops after a certain extent.