gpt4 book ai didi

reactjs - Intersection Observer API 进入无限渲染循环

转载 作者:行者123 更新时间:2023-12-03 23:39:54 27 4
gpt4 key购买 nike

当用户开始滚动时,我试图使用相交观察器 API 有条件地显示 CSS 网格中的项目,但它似乎进入了无限渲染循环。这是我的代码。
这是link到我在 StackBlitz 上的实时代码
此外,我试图实现的目标不是在可以避免的情况下在屏幕上渲染太多项目。我不确定 display: none实际上使浏览器的工作更少。如果这不是正确的方法,请告诉我。
感谢您阅读我的问题。任何帮助都受到高度赞赏。

最佳答案

该组件未按您预期的方式工作,因为您对所有项目使用相同的引用。您可以使用 ref存储引用数组或使用列表项逻辑创建组件。
如果不想同时渲染所有项目,可以渲染一部分(100),每次渲染scroll到最后,再渲染 100 次,依此类推。我建议
您使用 React.memo避免在每次状态更新时渲染项目:
PortfolioItem.js

const PortfolioItem = React.memo(({ ix }) => {
const ref = useRef();
const [inViewRef, inView] = useInView({
threshold: 1,
rootMargin: '0px',
});
const setRefs = useCallback(
(node) => {
ref.current = node;
inViewRef(node);
},
[], //--> empty dependencies
);

return ( <GridItem bg={inView?"red.100":"blue.100"} ref={setRefs} _last={{ mb: 4 }} >
<Center border={1} borderColor="gray.100" borderStyle="solid" h={16} w="100%">
Item {ix}
</Center>
</GridItem>)
});
PortfolioList.js
export const PortfolioList = ({ 
title,
count = 100
}: PortfolioListProps) => {
const ref = useRef(null);
const items = [...Array(1000)];
const [index, setIndex] = useState(count);

useEffect(()=> {
const grid = ref.current;
function onScroll(){
if(grid.offsetHeight + grid.scrollTop >= grid.scrollHeight) {
setIndex(prev => prev+count);
}
}
grid.addEventListener("scroll", onScroll);
return ()=> {
grid.removeEventListener("scroll", onScroll);
}
}, []);

return (
<Box
w="100%"
mx="auto"
rounded={{ md: `lg` }}
bg={mode(`white`, `gray.700`)}
shadow="md"
overflow="hidden"
>
<Flex align="center" justify="space-between" px="6" py="4">
<Text as="h3" fontWeight="bold" fontSize="xl">
{title}
</Text>
</Flex>
<Divider />
<Grid
p={4}
gap={4}
templateColumns="1fr 1fr 1fr 1fr"
templateRows="min-content"
maxH="500px"
minH="500px"
overflowY="auto"
id="list"
ref={ref}
>
{items.slice(0,index).map((pt,ix) => (
<PortfolioItem ix={ix} key={`Postfolio__item-${ix}`}/>
))
}
</Grid>
</Box>
);
};
Working example

关于reactjs - Intersection Observer API 进入无限渲染循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66503841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com