交集观察器 无法读取未定义的属性"当前"



我正试图在我的项目中实现IntersectionObserver,但收到一个错误Cannot read property 'current' of undefined。我做错了什么?

useOnScreen.js

const useOnScreen = ({ref, rootMargin = "0px", }) => {
const [isIntersecting, setIntersecting ] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIntersecting(entry.isIntersecting)
},
{
rootMargin,
}
);
if(ref.current) {
observer.observe(ref.current);
}
return () => {
observer.unobserve(ref.current)
}
}, [])
return isIntersecting;
};
export default useOnScreen;

App.js

import { useRef } from 'react';
import useOnScreen from './useOnScreen';

const App = ()
const ref = useRef();
const onScreen = useOnScreen(ref);

return (
<div ref={ref}>
onScreen ? "AAAAA" : "BBBBBB" 
</div>
)

问题是,在初始渲染时,ref将是undefined,并且您正在尝试访问它上的属性。您可以这样更新您的检查:

if (ref?.current) {
observer.observe(ref.current);
}

或者这个:

if (ref && ref.current) {
observer.observe(ref.current);
}

最新更新