反应 JS window.requestAnimationFrame(更新)

React JS window.requestAnimationFrame(update)

我在 React JS 上使用 Flickity 插件,一切正常。但是,我想创建像 https://brand.uber.com 这样的滑块(Best-in-class 示例部分)。

https://github.com/metafizzy/flickity/issues/77 上发布的解决方法示例有效,但我对播放和暂停功能有疑问。

问题是window.requestAnimationFrame(更新);在考虑暂停之前重新渲染组件。我尝试过本地状态和 redux,但它在我发送之前重新渲染。我正在使用下面的函数 comp 和代码。

 const carouselIsScrolling = useSelector(isServicesScrolling);
  const servicesCategoriesSel = useSelector(getServiceCategories);
  const carousel = useRef(null);
  const dispatch = useDispatch();

  const update = () => {

    if (carousel.current.flkty.slides && carouselIsScrolling) {
      carousel.current.flkty.x =
        (carousel.current.flkty.x - tickerSpeed) %
        carousel.current.flkty.slideableWidth;
      carousel.current.flkty.selectedIndex = carousel.current.flkty.dragEndRestingSelect();
      carousel.current.flkty.updateSelectedSlide();
      carousel.current.flkty.settle(carousel.current.flkty.x);
      window.requestAnimationFrame(update);
    }
  };

  const pause = () => {
    dispatch(app.toggleServiceScroller(false));
    window.cancelAnimationFrame(window.requestAnimationFrame(update));
  };

  const play = () => {
    if (!carouselIsScrolling) {
      dispatch(app.toggleServiceScroller(true));
      window.requestAnimationFrame(update);
    }
  };

  useEffect(() => {
    carousel.current.flkty.on("dragStart", () => {
      dispatch(app.toggleServiceScroller(false));
    });
    dispatch(app.toggleServiceScroller(false));
    update();
  }, []);

原因是我正在使用状态更改 carouselIsScrolling,等待重新渲染使用,但重新渲染导致它重置为初始值。

我改为使用

const carouselIsScrolling = useRef(true);

 if (!carouselIsScrolling.current) return;

现在可以使用了。