使用Next.js 13+GlideJS实现轮播时遇TypeError错误求助
Next.js 13 + GlideJS 轮播组件报错:
TypeError: Cannot destructure property 'DynamicServerError' of 'serverHooks' as it is undefined 我正在使用Next.js 13搭配GlideJS实现轮播功能,采用wind-ui提供的轮播组件,但运行时出现上述错误。请问是否有人遇到并解决过该问题?
以下是组件源码:
'use client' import React, { useEffect } from "react" import Glide from "@glidejs/glide" export default function CarouselLogo() { useEffect(() => { const slider = new Glide(".glide-09", { type: "carousel", autoplay: 1, animationDuration: 4500, animationTimingFunc: "linear", perView: 3, classes: { nav: { active: "[&>*]:bg-wuiSlate-700", }, }, breakpoints: { 1024: { perView: 2, }, 640: { perView: 1, gap: 36, }, }, }).mount() return () => { slider.destroy() } }, []) return ( <> <div className="glide-09 relative w-full"> <div data-glide-el="track"> <ul className="whitespace-no-wrap flex-no-wrap [backface-visibility: hidden] [transform-style: preserve-3d] [touch-action: pan-Y] [will-change: transform] relative flex w-full overflow-hidden p-0"> <li> <img src="https://Tailwindmix.b-cdn.net/carousel/logos/carousel-logo-image-1.svg" className="m-auto h-20 max-h-full w-auto max-w-full" /> </li> </ul> </div> </div> </> ) }
解决办法
这个错误本质是Next.js 13 App Router中,GlideJS的初始化逻辑意外在服务器端执行导致的,即使加了'use client'也可能因为模块导入时机的问题触发。可以尝试以下几种方案:
动态导入GlideJS
把直接导入改成在useEffect里动态加载,确保只在客户端执行:'use client' import React, { useEffect } from "react" export default function CarouselLogo() { useEffect(() => { import("@glidejs/glide").then(({ default: Glide }) => { const slider = new Glide(".glide-09", { type: "carousel", autoplay: 1, animationDuration: 4500, animationTimingFunc: "linear", perView: 3, classes: { nav: { active: "[&>*]:bg-wuiSlate-700", }, }, breakpoints: { 1024: { perView: 2, }, 640: { perView: 1, gap: 36, }, }, }).mount() return () => slider.destroy() }) }, []) // 其余JSX部分不变 }使用Ref获取DOM元素
避免用类选择器查找元素,改用useRef确保DOM存在后再初始化:'use client' import React, { useEffect, useRef } from "react" export default function CarouselLogo() { const glideContainer = useRef(null) useEffect(() => { if (!glideContainer.current) return import("@glidejs/glide").then(({ default: Glide }) => { const slider = new Glide(glideContainer.current, { // 原配置不变 }).mount() return () => slider.destroy() }) }, []) return ( <> <div ref={glideContainer} className="glide-09 relative w-full"> {/* 其余JSX部分不变 */} </div> </> ) }检查依赖版本
确保@glidejs/glide是最新版本,或者尝试降级到适配Next.js 13的稳定版本,避免版本兼容问题。
内容的提问来源于stack exchange,提问作者Neville Lemein
相关产品推荐
相关产品推荐

