3

以下是我试图了解交叉点观察者的示例:

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>
  );
}

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

4

1 回答 1

0

您的 useEffect 有第二个参数:

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

   ^^
   ||

These here.

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

于 2019-09-04T07:26:16.673 回答