为什么我的页面在React中滚动到底部时重新渲染(刷新)?



我想问一些问题,因为我真的不知道为什么会发生这种情况。为什么我的页面在滚动到底部时重新渲染(刷新)?我的意思是,它像我想要的那样获取更多的项,但它是用refresh更新的,我不希望那样。代码如下:https://pastebin.com/ESu7ijiy

useEffect(() => {
const event = window.addEventListener("scroll", () => {
if ((isLoading && window.innerHeight + window.scrollY) >= document.body.scrollHeight - 2){
setPage((oldPage) => {
return oldPage + 1;
});
}
});
return () => window.removeEventListener("scroll", event);
}, []);

因为在第二个useEffect中你写了这个

setPage((oldPage) => {
return oldPage + 1;
});
}

在这里,你通过向下滚动来增加page。因为在你的第一个useEffect你传递page作为第二依赖

useEffect(() => {
getPhotosFromInitUrl();
}, [searchValue, page]);

第一个useEffect将调用getPhotosFromInitUrl()每次页面将改变page在你的第二个useEffect

我找到了解决方案——问题出在文件的结构上

<Container component="main" className="App">
<SearchForm
value={value}
setValue={setValue}
handleSubmit={handleSubmit}
/>
<Box component="section" style={{ marginTop: "50px" }}>
{isLoading && <h2>Loading...</h2>}
<Grid container spacing={5}>
{photos.map((photo) => {
return (
<Grid item xs={12} md={6} lg={4}>
<SinglePhoto {...photo} />
</Grid>
);
})}
</Grid>
</Box>
</Container>

最新更新