React JS window.requestAnimationFrame(update)



我在React JS和所有作品上使用Flickity插件。然而,我想创建滑块https://brand.uber.com(最佳范例部分(。

发布在上的解决方法示例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;

现在它起作用了。

最新更新