reactjs Swiper组件在React中不工作并引发错误

vnjpjtjt  于 2023-02-12  发布在  React
关注(0)|答案(3)|浏览(366)

所以我跟着Traversity Media的一门课程,叫做“React Front To Back 2022”,在第5和第6个视频的第16节课程中,他使用了Swiper组件。我一步一步地跟着,但在最后,它抛出了一个错误,所以经过一点思考和谷歌搜索,我决定看看他发布的项目的GitHub存储库的解决方案,我比较了代码,看起来是一样的,我复制了它,但是,它仍然抛出错误,没有呈现页面。
我在任何地方都找不到修复方法(谷歌,文档,YouTube等),所以希望有人能在这里帮助我。提前感谢你的帮助。
错误:

init-swiper.js:25 Uncaught TypeError: Cannot read properties of undefined (reading 'pagination')
at mountSwiper (init-swiper.js:25:1)
at swiper.js:136:1
at commitHookEffectListMount (react-dom.development.js:23049:1)
at invokeLayoutEffectMountInDEV (react-dom.development.js:25010:1)
at invokeEffectsInDev (react-dom.development.js:27304:1)
at commitDoubleInvokeEffectsInDEV (react-dom.development.js:27280:1)
at flushPassiveEffectsImpl (react-dom.development.js:27007:1)
at flushPassiveEffects (react-dom.development.js:26935:1)
at performSyncWorkOnRoot (react-dom.development.js:26032:1)
at flushSyncCallbacks (react-dom.development.js:12009:1)

react_devtools_backend.js:4026 The above error occurred in the <Swiper> component:

at http://localhost:3000/static/js/bundle.js:131862:66
at Slider (http://localhost:3000/static/js/bundle.js:1549:66)
at main
at div
at Explore
at Routes (http://localhost:3000/static/js/bundle.js:120121:24)
at Router (http://localhost:3000/static/js/bundle.js:120046:30)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:118774:23)
at App

Uncaught TypeError: Cannot read properties of undefined (reading 'pagination')
at mountSwiper (init-swiper.js:25:1)
at swiper.js:136:1
at commitHookEffectListMount (react-dom.development.js:23049:1)
at invokeLayoutEffectMountInDEV (react-dom.development.js:25010:1)
at invokeEffectsInDev (react-dom.development.js:27304:1)
at commitDoubleInvokeEffectsInDEV (react-dom.development.js:27280:1)
at flushPassiveEffectsImpl (react-dom.development.js:27007:1)
at flushPassiveEffects (react-dom.development.js:26935:1)
at performSyncWorkOnRoot (react-dom.development.js:26032:1)
at flushSyncCallbacks (react-dom.development.js:12009:1)

代码:

import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { collection, getDocs, query, orderBy, limit } from 'firebase/firestore'
import { db } from '../firebase.config'
import SwiperCore, { Navigation, Pagination, Scrollbar, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper-bundle.css'
import Spinner from './Spinner'
SwiperCore.use([Navigation, Pagination, Scrollbar, A11y])

function Slider() {
  const [loading, setLoading] = useState(true)
  const [listings, setListings] = useState(null)

  const navigate = useNavigate()

  useEffect(() => {
    const fetchListings = async () => {
      const listingsRef = collection(db, 'listings')
      const q = query(listingsRef, orderBy('timestamp', 'desc'), limit(5))
      const querySnap = await getDocs(q)

      let listings = []

      querySnap.forEach((doc) => {
        return listings.push({
          id: doc.id,
          data: doc.data(),
        })
      })

      setListings(listings)
      setLoading(false)
    }

    fetchListings()
  }, [])

  if (loading) {
    return <Spinner />
  }

  if (listings.length === 0) {
    return <></>
  }

  return (
    listings && (
      <>
        <p className='exploreHeading'>Recommended</p>

        <Swiper slidesPerView={1} pagination={{ clickable: true }}>
          {listings.map(({ data, id }) => (
            <SwiperSlide
              key={id}
              onClick={() => navigate(`/category/${data.type}/${id}`)}
            >
              <div
                style={{
                  background: `url(${data.imgUrls[0]}) center no-repeat`,
                  backgroundSize: 'cover',
                }}
                className='swiperSlideDiv'
              >
                <p className='swiperSlideText'>{data.name}</p>
                <p className='swiperSlidePrice'>
                  ${data.discountedPrice ?? data.regularPrice}{' '}
                  {data.type === 'rent' && '/ month'}
                </p>
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      </>
    )
  )
}

export default Slider

GitHub link to the repo

csbfibhn

csbfibhn1#

I'm currently facing same issue while following the course On udemy can't seem to find any difference in my code. The fix was, I updated Swiper to the latest version using npm i swiper@latest then changed my imports to import  {Navigation, Pagination, Scrollbar, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/css'
 and finally updated my swiper components to <Swiper
        slidesPerView={1}
        pagination={{ clickable: true }}
        modules={[Navigation, Pagination, Scrollbar, A11y]}
        navigation
        scrollbar={{ draggable: true }}
      >
        {listing.imgUrls.map((url, index) => (
          <SwiperSlide key={index}>
            <div
              style={{
                background: `url(${listing.imgUrls[index]}) center no-repeat`,
                backgroundSize: 'cover',
                minHeight: '26rem',
              }}
              className='swiperSlideDiv'
            ></div>
          </SwiperSlide>
        ))}
      </Swiper>
e3bfsja2

e3bfsja22#

尝试切换切换器包的版本。
查看周年纪念回购协议的package.json:https://github.com/bradtraversy/house-marketplace/blob/main/package.json

7jmck4yq

7jmck4yq3#

它的到来是由于<react.strictmode>删除它从index.js和它的工作,但我不知道为什么严格模式导致这个错误

相关问题