You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Swiper组件挂载报pagination属性读取错误

问题根因

报错由Swiper版本不兼容导致。教程和参考项目使用的是Swiper 6.x/7.x 旧版本API,本地安装依赖时默认拉取了Swiper 8+ 新版本,新版本对模块注册、样式引入逻辑做了破坏性变更,旧写法运行时就会抛出Cannot read properties of undefined (reading 'pagination')错误,哪怕直接复制原仓库代码也会触发问题——因为原仓库锁的是旧版本依赖,本地安装时未指定版本就会拉取不兼容的新版。

修复方案

两种方案二选一即可:

方案1:降级到教程匹配版本(无需修改业务代码)

  • 先卸载当前安装的新版Swiper
npm uninstall swiper
  • 安装和教程兼容的指定版本
npm install swiper@6.8.4
  • 安装完成后重启开发服务,原有代码不需要任何调整即可正常运行。

方案2:保留新版Swiper,适配新API修改代码

如果不想降级版本,按照Swiper 8+的语法规则调整代码即可:

  • 删除旧版本的SwiperCore模块注册逻辑
  • 用到的功能模块直接通过Swiper组件的modules属性传入
  • 替换样式文件的引入路径

修改后的完整组件代码:

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 { Navigation, Pagination, Scrollbar, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/css'
import 'swiper/css/pagination'
import Spinner from './Spinner'

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 }}
          modules={[Navigation, Pagination, Scrollbar, A11y]}
        >
          {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

修改完成后保存文件,重启开发服务即可正常渲染轮播组件。


内容的提问来源于stack exchange,提问作者Mohamed Chokor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 07:36:18