我使用 firebase 数据库来存储数据,并使用 useEffect Hook 挂载数据。但它向我发出了缺少依赖项数组的警告。
每当我传递依赖项时,它就会进入无限循环
const Channels = props => {
const [channels, setChannels] = useState([]);
const [firstLoad, setFirstLoad] = useState(false);
useEffect(() => {
let loadedChannels = [];
firebase
.database()
.ref("channels")
.on("child_added", snap => {
loadedChannels.push(snap.val());
setChannels(channels.concat(loadedChannels));
setFirstLoad(true);
});
}, []);
}
最佳答案
编辑:再看一遍,您收到该错误的原因是因为您在 useEffect()
运行时关闭了 channels
的初始值第一次。因此,channels
确实应该位于您的依赖项数组中,因为当该值发生变化时,您会希望新值从那时起反射(reflect)在状态更新中。您试图使用 loadedChannels
数组来绕过它,这是一种奇怪的反模式。
我实际上建议您将其调整为类似这样的内容。请注意现在如何使用函数调用 setChannels
,该函数将 channels
的实际最新值作为参数,并允许您更新该值不会因关闭而过时。
另请注意 useEffect()
函数如何返回另一个函数,该函数在组件卸载时删除 Firebase 事件监听器!
const Channels = props => {
const [channels, setChannels] = useState([]);
const [firstLoad, setFirstLoad] = useState(false);
useEffect(() => {
function onFirebaseUpdate(snap) {
setChannels((previousChannelsValue) => {
return previousChannelsValue.concat(snap.val())
});
setFirstLoad(true);
}
firebase
.database()
.ref("channels")
.on("child_added", onFirebaseUpdate);
// You'll want to remove this listener when the component unmounts...
return function() {
firebase
.database()
.ref("channels")
.off("child_added", onFirebaseUpdate);
}
}, []);
}
如果您仍然收到警告,可能是因为 firebase
或 setChannels
是函数中的引用,应考虑将其添加到依赖项数组中。但在这种情况下,您(希望)知道自己在做什么以及发生了什么,并且可以忽略警告。
关于javascript - React Hook useEffect 缺少依赖项数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56796678/