如何使用 React hooks 初始化 Swiper?

How to initialize Swiper using React hooks?

我正在使用 React hooks 和 Swiper (SwiperJS Link) 库。但是,初始化时出错。谁能帮忙? 我试过这样-

    let mySwiper; 
    useEffect(() => {
    mySwiper = new Swiper('.swiper-container', {
        loop: true,
        slidesPerView: '2',
        centeredSlides: true,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
    });
})

但是,React 给了我这个警告并且没有正确初始化滑块。警告-

Assignments to the 'mySwiper' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.

最后,我的模板 -

<div className="swiper-container">
   <div className="swiper-wrapper">
      {
         places.map((item, index) => (
          <div key={index} className="swiper-slide"
            onTouchStart={() => { onPlaceSelect(index) }}
            onTouchCancel={() => { onPlaceSelect(index) }}>
              <Package
                 className="swiper-slide"
                 key={index}
                 backgroundImage={Background}
                 modelImage={Model}
                 title="Learn  traditionally"
                 price="15"
                 ref={myRef.current[index]} />
          </div>))}
   </div>
</div>

那么,使用 React hooks 初始化它的正确方法是什么?

您的 useEffect 将在每次渲染中 运行,每次创建新的 Swiper 实例。尝试将 swiper 实例存储在 state 中,并且 运行 useEffect 仅一次。

let [mySwiper, setMySwiper] = useState(null) 
useEffect(() => {
  let mySwiper = new Swiper('.swiper-container', {
     loop: true,
     slidesPerView: '2',
     centeredSlides: true,
     pagination: {
        el: '.swiper-pagination',
        clickable: true,
     },
  });
  setMySwiper(mySwiper) 
}, [])

[] 作为 useEffect 的第二个参数确保,效果 运行 只有一次,即在组件安装期间。