React Swiper slideChange异常:数据更新后自动跳至最后一页问题
问题描述
当前使用Swiper实现轮播加载更多功能,每页展示10条数据,获取第二页数据后总计20条。预期从第11条(索引10)开始手动切换轮播,但实际获取第二页数据后,轮播自动跳至第20条(最后一页)。
相关代码:
initSwiper = (index) => { const swiper = new Swiper(".mySwiperCarousel", { initialSlide: index || 0, // loop: true, // spaceBetween: 10, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", disabledClass: 'my-button-disabled', }, pagination: { el: '.swiper-pagination-carousel', }, observer: true, observeParents: true, preloadImages: false, slidesPerView: 'auto', lazy: true, watchSlidesVisibility: true, watchSlidesProgress: true, speed: 0 }); swiper.on("slideChange",async (e)=>{ const {photos, photosPageInfo} = this.state if ( e.activeIndex === photos.length - 1 && photosPageInfo && photosPageInfo.hasNext) { this.POST_DATA.pageInfo.num++; await this._getDataForSwiper(); swiper.update() } }); }
解决方法
问题出在调用swiper.update()时,Swiper会重新计算轮播状态,默认会将活跃索引调整为新数据总长度对应的位置,导致自动跳转到最后一页。通过记录当前活跃索引,更新数据后手动恢复索引即可解决:
修改slideChange事件处理逻辑:
swiper.on("slideChange",async (e)=>{ const {photos, photosPageInfo} = this.state // 记录当前的活跃索引 const currentActiveIndex = e.activeIndex; if ( currentActiveIndex === photos.length - 1 && photosPageInfo && photosPageInfo.hasNext) { this.POST_DATA.pageInfo.num++; await this._getDataForSwiper(); // 先更新Swiper状态 swiper.update(); // 手动跳回之前记录的活跃索引 swiper.slideTo(currentActiveIndex); } });
另外可以检查speed: 0的配置,瞬间切换可能会导致索引计算异常,如果上述方法生效可保留该配置,若仍有问题可尝试将speed设置为合理值(比如300)。
内容的提问来源于stack exchange,提问作者n wei
相关产品推荐
相关产品推荐

