[Swiper]在React中使用Swiper时注意销毁实例

swiper版本号:

json 复制代码
{
  "swiper": "^4.4.2",
}

在useEffect中初始化swiper实例,由于依赖项的变更,可能会重复初始化:

javascript 复制代码
useEffect(() => {
  swiper.current = new Swiper('#mainSwiper', {
    autoplay: {
      delay: 3000,//3秒切换一次
    },
    on: {
      slideChange: function() {
        //...
      },
    },
  });
}, [swiperRef, tabList, swiperList, unmountedRef]);

如果tabList、swiperList有变更,会导致重复创建实例。

我们查看swiper官方文档,找到相关方法:

据此在return中销毁实例:

javascript 复制代码
useEffect(() => {
  swiper.current = new Swiper('#mainSwiper', {
    autoplay: {
      delay: 3000,//3秒切换一次
    },
    on: {
      slideChange: function() {
        //...
      },
    },
  });
  return () => {
    //增加销毁实例的方法,防止多次实例化
    if (swiper.current && isFunction(swiper.current.destroy)){
      try {
        swiper.current.destroy();
        console.log('swiper destroy')
      } catch (e) {
        console.error('swiper destroy error', e)
      }
    }
  }
}, [swiperRef, tabList, swiperList, unmountedRef]);

也许可以使用updateSlides()来更新实例,目前还未使用过该方法。

相关推荐
蜡笔小柯南17 分钟前
解决:npm install报错,reason: certificate has expired
前端·npm·node.js
lqj_本人1 小时前
鸿蒙OS&UniApp制作多选框与单选框组件#三方框架 #Uniapp
前端·javascript·uni-app
@PHARAOH2 小时前
WHAT - 前端开发流程 SOP(标准操作流程)参考
前端·领导力
松树戈3 小时前
plus-ui&RuoYi-Vue-Plus 基于pgSql本地运行实践
前端·vue.js·spring boot·ui
new6669993 小时前
css画图形
前端·css
Yvonne爱编码4 小时前
CSS- 1.1 css选择器
前端·css·状态模式·html5·hbuilder
山河故人1634 小时前
uniapp使用npm下载
前端·npm·uni-app
-曾牛5 小时前
基于微信小程序的在线聊天功能实现:WebSocket通信实战
前端·后端·websocket·网络协议·微信小程序·小程序·notepad++
一口一个橘子5 小时前
[ctfshow web入门] web72
前端·web安全·网络安全
Web极客码5 小时前
如何使用WordPress SEO检查器进行实时内容分析
前端·seo·wordpress