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

升级Next.js 13后使用Swiper出现useState相关TypeError错误求助

解决Next.js 13升级后Swiper组件的TypeError: Cannot read properties of null (reading 'useState')错误

核心解决方案

在你的页面组件(index.js)顶部添加'use client'指令,修改后的代码如下:

'use client';

// Import Swiper React components
import { Swiper, SwiperSlide } from 'swiper/react';

// Import Swiper styles
import 'swiper/css';

export default () => {
  return (
    <Swiper
      spaceBetween={50}
      slidesPerView={3}
      onSlideChange={() => console.log('slide change')}
      onSwiper={(swiper) => console.log(swiper)}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
    </Swiper>
  );
};

问题原因解释

Next.js 13的App Router默认将所有组件视为服务器组件,服务器组件在服务器端渲染,不支持React Hooks(如useState)。而你使用的Swiper React组件内部依赖Hooks实现功能,当它作为服务器组件运行时,会因为缺少客户端React环境导致Hooks调用失败,从而抛出堆栈中显示的错误。

添加'use client'指令后,组件会被标记为客户端组件,在浏览器端执行,此时React Hooks可以正常初始化和运行,错误即可解决。

额外排查建议(可选)

如果添加指令后仍有问题,可以检查:

  • 确认项目中没有多个版本的React或React DOM依赖(可通过npm ls react查看依赖树)
  • 确保Swiper版本与Next.js 13兼容(推荐使用最新稳定版Swiper)

内容的提问来源于stack exchange,提问作者Ali EXE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:31:12