Next13 App Router中如何为loading.js添加'use client'以使用Lottie组件
解决Next.js 13 App Router中loading.tsx里Lottie组件不生效的问题
确保子组件也是客户端组件:你的
LoginLoadingComponent必须添加'use client'指令,因为@lottiefiles/react-lottie-player依赖浏览器环境的API,所有使用它的组件都必须标记为客户端组件,仅父组件加'use client'不够。验证Lottie资源的导入方式:在App Router中,静态资源(比如Lottie的JSON文件)需要通过ES模块导入,不能直接写相对路径。示例:
// 在LoginLoadingComponent或loading.tsx中 import loadingAnimation from '@/public/your-loading-animation.json'; // 然后在Player组件中使用 <Player src={loadingAnimation} autoplay loop />重新安装依赖:有时候依赖安装不完整会导致问题,执行以下命令重装相关包:
npm install @lottiefiles/react-lottie-player lottie-web检查loading.tsx的位置:确认
loading.tsx放在正确的路由段目录下,比如如果是登录页面的加载状态,应该放在app/login/loading.tsx,这样Next.js才会在该路由加载时渲染这个loading组件。简化代码排查问题:暂时跳过
LoginLoadingComponent,直接在loading.tsx中写Lottie的基础代码,看是否能正常运行:'use client'; import { Player } from '@lottiefiles/react-lottie-player'; import loadingAnim from '@/public/loading.json'; export default function Loading() { return ( <div className="flex h-screen items-center justify-center"> <Player src={loadingAnim} autoplay loop style={{ width: '150px', height: '150px' }} /> </div> ); }升级Next.js版本:部分早期的Next.js 13版本存在客户端组件的兼容性bug,升级到最新稳定版可能解决问题:
npm update next
内容的提问来源于stack exchange,提问作者jeong k
相关产品推荐
相关产品推荐

