Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将IntersectionObserver与React一起使用?_Javascript_Reactjs_Use Effect_Intersection Observer - Fatal编程技术网

Javascript 如何将IntersectionObserver与React一起使用?

Javascript 如何将IntersectionObserver与React一起使用?,javascript,reactjs,use-effect,intersection-observer,Javascript,Reactjs,Use Effect,Intersection Observer,我目前有一个useEffect,其中包含多个功能。我决定创建一个无限滚动功能,但我很难做到: 这就是我所拥有的: const [posts, setPosts] = useState([]); const [page, setPage] = useState(1); const ref = { current: null }; useEffect(() => { getPosts(params).then((result) => { setPosts(result);

我目前有一个useEffect,其中包含多个功能。我决定创建一个无限滚动功能,但我很难做到:

这就是我所拥有的:

const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
const ref = { current: null };
useEffect(() => {
  getPosts(params).then((result) => {
    setPosts(result);
  }).catch((err) => {});
  ...
  ...
  ...
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      setPage(next);
    }
  }, {
    threshold: 0.1
  }
                                           );
  observer.observe(ref.current);
}, [getPosts, ..., ..., ref])

/// FETCHED POSTS
{posts?.length > 0 ? (
  posts.map((post, index) => (
    <Single
        key={post._id}
        post={post}
        postId={postId}
        setObjects={setPosts}
        objects={posts}
        setTotalResult={setTotalResults}
    />
  ))
) : (
  <NothingFoundAlert />
)}
/// BUTTON
<button ref={ref} style={{ opacity: 0 }}>
    Load more
</button>
以前有人用过这个吗?

const ref={current:null}
//到
const ref=useRef()
应修复此问题,因为错误表明您试图观察分配的
null
,而不是HTMLElement


在React中使用IntersectionObserver时,我建议使用为其创建的钩子,如。

尝试更改
const ref={current:null}
const ref=useRef(null)
并将整个
IntersectionObserver
子句包装在
if(ref.current)
条件中
TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.