我遇到了这样的挑战,我想要将数组的一部分加载到一个名为"loadedData"的新数组中,并且只显示loadedData,因为组件非常繁重.
然而,在第一次加载时,我在第一次加载时遇到了很多问题,因为useEffect似乎把它搞砸了.第一次加载将发生两次,并在每次渲染时将数组上的第一个数据推送一次.如果我删除了"reactStrictMode",它就会正常工作,但我不想在不了解其含义的情况下"作弊".有比我更了解的人把它放在那里是有原因的..
在初始加载期间,isLoding状态不会阻止第二次运行-这是我在其他与此问题相关的线程中倾向于得到的建议.
有人知道为什么第一个useEffect会忽略isLoding状态吗?该怎么办?
// Try to load what is visible, but not more
const [loadedData, setLoadedData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const addMoreData = async () => {
if (loadedData.length >= data.length) return;
const startIndex = loadedData.length;
const preferredLoadLength = 1;
const endIndex = startIndex + preferredLoadLength;
const newData = data.slice(startIndex, endIndex);
setLoadedData((prev) => [...prev, ...newData]);
};
// Check on mount and after a fetch to see if the table is already scrolled to the bottom and immediately needs to fetch more data
useEffect(() => {
const { scrollHeight, scrollTop, clientHeight } = tableContainerRef.current;
if (
scrollHeight == clientHeight &&
scrollTop == 0 &&
loadedData.length < data.length
) {
const addNewDataFunction = async () => {
if (isLoading) {
return;
}
setIsLoading(true);
await addMoreData();
setIsLoading(false);
};
addNewDataFunction();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data.length, loadedData.length, isLoading]);