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

Next.js 13:从loading.tsx获取Props值返回undefined的解决方案

Next.js 13中Suspense给loading.tsx传Props为undefined的解决办法

Next.js 13(App Router)的loading.tsx是页面/布局级的加载 fallback 组件,框架默认不支持直接从父组件接收Props,这是你遇到items值为undefined的核心原因。以下是具体解决方案:

方案1:直接在loading.tsx中使用固定预期值

如果items的预期值固定为8,无需动态传递,直接在loading.tsx中写死即可:

// app/character/loading.tsx
export default function Loading() {
  const items = 8;
  return (
    <div className="loading-state">
      <p>正在加载 {items} 个角色...</p>
      {/* 这里添加你的加载动画 */}
    </div>
  );
}

方案2:通过React Context传递动态值

如果items需要依赖fetch的数据长度,可通过Context在Suspense上层传递值:

步骤1:在页面组件中创建并提供Context

// app/character/page.tsx
import { Suspense, createContext } from 'react';
import Loading from './loading';
import CharacterContent from './character-content';

// 创建Context,设置默认值为8
const LoadingItemsContext = createContext<number>(8);

export default async function CharacterPage() {
  // 模拟fetch数据
  const res = await fetch('https://your-api-url/characters', { cache: 'force-cache' });
  const characters = await res.json();
  const itemsLength = characters.length; // 实际获取数据长度

  return (
    <LoadingItemsContext.Provider value={itemsLength}>
      <Suspense fallback={<Loading />}>
        <CharacterContent characters={characters} />
      </Suspense>
    </LoadingItemsContext.Provider>
  );
}

步骤2:在loading.tsx中读取Context值

// app/character/loading.tsx
'use client'; // 客户端组件才能使用useContext
import { useContext } from 'react';
import { LoadingItemsContext } from './page';

export default function Loading() {
  const items = useContext(LoadingItemsContext);
  return (
    <div className="loading-state">
      <p>正在加载 {items} 个角色...</p>
      {/* 加载动画 */}
    </div>
  );
}

关键说明

  • loading.tsx是框架自动触发渲染的fallback组件,并非你手动调用的组件,因此无法通过常规的组件Props传递数据。
  • 如果是服务器组件中的动态值,必须通过Context传递给客户端组件类型的loading.tsx(因为useContext需要在客户端组件中使用)。

内容的提问来源于stack exchange,提问作者Kevin Ang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:12:48