[이슈해결노트] scrollMagic - scrollInit / destroy()

이나현·2022년 10월 27일
0

오라운드

목록 보기
6/18
post-thumbnail

문제 상황

  • 스크롤 매직을 사용해 상세페이지 하단 푸터 기능을 추가함
  • 페이지 이동 후 새로운 상품의 상세페이지로 진입할 때, 푸터에 이벤트가 이중~삼중으로 걸리며 깜빡이는 현상 발생
  • 찾아보니 scrollmagic 이벤트의 start point와 end point가 여러번 생겨 새로고침을 하지 않는 이상, 이벤트가 여러개 걸린다는 것을 발견

해결 논리

  • 상세페이지를 나가면 이벤트를 삭제하고 상세페이지에 진입했을 때, 새로 생성하는 방향으로 이벤트를 걸고자함
  • 이게 안될 시, 자바스크립트로 scroll 높이를 측정해서 컴포넌트를 만들고 지우는 로직을 추가하고자 함

해결 과정

(1) scrollmagic 이벤트가 있는 파일에 이벤트 삭제 함수를 만듦

그 후, 이벤트가 적용되는 상세페이지 컴포넌트에 페이지를 나갔을 때, 이벤트 삭제 함수를 부르는 방법으로 해결

//product_ui.js(scrollmagic이 있는 파일)

var controller;
var scrollController;

var scrollInit = () => {
  controller = new ScrollMagic.Controller();

  scrollController  =  new ScrollMagic.Scene({triggerElement: '#mo_total_section',offset: 570})
    .addTo(controller)
    .on("enter", function () {
      $('.mo_purchase_footer').addClass('on');
    })
    .on("leave", function () {
      $('.mo_purchase_footer').removeClass('on');
    })
    // .addIndicators({
    //   name: "test"
    // })
}

var scrollDestroy = () => {
  scrollController.destroy(true);
  scrollController = null;

  controller.destroy(true);
  controller = null;
}
 React.useEffect(() => {
  if (typeof window !== 'undefined' && isMobile ) {
   scrollInit();
    }
   return () => {
	   if (typeof window !== 'undefined' && isMobile ) {
    scrollDestroy();
	    }
    };
  }, [isMobile, productDetailPageStore, productInfoOptionsStore]);
  • 여기서 발생한 문제!!!! scrollinit is undefined
  • 페이지가 렌더 됐을 때, scrollinit이 안불리는 문제 발생!

(2) try … catch문으로 에러처리

React.useEffect(() => {
    try {
      if (window && isMobile ) window.scrollInit();
    } catch (error) {console.log(error);}

    return () => {
      try {
        if (window && isMobile ) window.scrollDestroy();
      } catch (error) { console.log(error);}
    };
  }, [isMobile, productDetailPageStore, productInfoOptionsStore]);
profile
technology blog

0개의 댓글