gpt4 book ai didi

reactjs - 为什么 intersection observer 会在组件挂载时触发?

转载 作者:行者123 更新时间:2023-12-05 07:19:27 25 4
gpt4 key购买 nike

以下是我试图理解路口观察器的示例:

function Test(props) {
const loadingRef = useRef(null);
useEffect(() => {
let options = {
root: null,
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(handleIntersection, options);
observer.observe(loadingRef.current)
}, [])

function handleIntersection(x, y) {
console.log("Why this triggers on component mount?");
}
return (
<div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div style={{width: '100%', height: '100px', background: '#c4c4c4', borderBottom: '1px solid #f4f4f4'}}></div>
<div ref={loadingRef}></div>
</div>
);
}

我不明白为什么即使目标元素不与源元素相交也会在组件挂载时触发。

最佳答案

您的 useEffect 有第二个参数:

useEffect(() => {
let options = {
root: null,
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(handleIntersection, options);
observer.observe(loadingRef.current)
}, [])

^^
||

These here.

这意味着它在组件挂载时运行。有一部分Hooks FAQ在 reactjs.org 上提到了这一点。

关于reactjs - 为什么 intersection observer 会在组件挂载时触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783117/

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