Programing

효과()를 올바르게 사용하는 방법?

c10106 2022. 3. 11. 22:05
반응형

효과()를 올바르게 사용하는 방법?

나는 스크롤을 해서 스타일을 바꾸고 싶다.

이 코드는 제대로 작동하지 않는다.내가 너무 많이 굴리고 너무 빨리 굴리면, 브라우저가 정지하고, 작동이 중단될 것이다.

나는 내가 사용했던 것 같다.useEffect()틀렸어. 어떻게 하면 이 문제를 해결할 수 있을까.

const ArticleItem = ({title, content, active, chapter, program, id, scrollPos}) => {
  const ref = useRef(null);
  const client = useApolloClient();

  useEffect(() => {
    if(ref.current.offsetTop <= (scrollPos + 200)) {
      client.writeData({data: {
        curChapter: chapter.num,
        curArticle: id,
        curProgram: program.name
      }});
    }
  });

  if(active === false)
    return ( // Inactive Article
      <div className='section-item' ref={ref}>
        <h2>{title.toUpperCase()}</h2>
        <ReactMarkdown source={content} />
        <br />
      </div>
    )
  return (  // Active Article
    <div className='section-item active' ref={ref}>
      <h2>{title.toUpperCase()}</h2>
      <ReactMarkdown source={content} />
      <br />
    </div>
  )
}

결과적으로, 나는 이 경고에 직면했다.

경고: 최대 업데이트 깊이를 초과함이 문제는 구성 요소가 setState inside useEffect를 호출하지만 useEffect 중 하나에 종속성 배열이 없거나 모든 렌더에서 종속성 중 하나가 변경될 때 발생할 수 있다.

이게 이슈의 이유인 것 같은데?!

위에서 언급한 내용에 따라 다음에 대한 종속성 어레이를 포함하십시오.useEffect또한. 현재의 방식으로는 무한정 달리고 있다.아마도 당신은 포함하기를 원할 것이다.scrollPos그래서 그것은 단지 한 번만 촉발될 것이다.scrollPos변하고 있다.

다음을 시도해 보십시오.

useEffect(() => {
    if(ref.current.offsetTop <= (scrollPos + 200)) {
      client.writeData({data: {
        curChapter: chapter.num,
        curArticle: id,
        curProgram: program.name
      }});
    }
}, [scrollPos]);

이게 도움이 되었으면 좋겠어!

음, 문제는 항상 당신이 사용할 수 있는scroll이벤트 수신기 및 이 이벤트가 트리거될 때 변경하십시오.

const [scrollItem, setScrollItem] = useState(null);

const handleScroll() {
  if(scrollItem) {
     // logic goes here
  }
}

useEffect(() => {
  window.addEventListener('scroll', handleScroll);

  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
}, []); // initialize event only once

return (
   <div ref={setScrollItem}>
      ...
   </div>
);

편집

그 해결책은 피하라, @norbitrial이 옳다.

참조URL: https://stackoverflow.com/questions/61011130/how-to-use-useeffect-correctly

반응형