next中服务端组件共享接口数据

1、首先创建一个共享的数据获取文件:

getSharedData.ts

javascript 复制代码
import { cache } from 'react'
import { getAnchorArticle } from '@/service/supabase/api/article'
import { getMaterialCategory } from '@/service/supabase/api/materials'
import { getTechnologyCategory } from '@/service/supabase/api/technology'

export type SharedData = {
  anchorArticle: any // 替换为实际的类型
  materialCategory: any // 替换为实际的类型
  technologyCategory: any // 替换为实际的类型
}

export const getSharedData = cache(async (): Promise<SharedData | null> => {
  try {
    const [anchorArticle, technologyCategory, materialCategory] = await Promise.all([
      getAnchorArticle(),
      getTechnologyCategory(),
      getMaterialCategory(),
    ])

    return {
      anchorArticle,
      technologyCategory,
      materialCategory,
    }
  } catch (error) {
    console.error('Error fetching shared data:', error)
    return null
  }
})

2、然后在需要使用这些数据的服务端组件中:

index.tsx

javascript 复制代码
import { getSharedData } from '@/lib/getSharedData'

const Header = async () => {
  const data = await getSharedData()
  const { anchorArticle, technologyCategory, materialCategory } = data!

  return (
    // ... rest of the component
  )
}

3、在其他服务端组件中也可以直接使用:

SomeOtherServerComponent.tsx

javascript 复制代码
import { getSharedData } from '@/lib/getSharedData'

const SomeOtherServerComponent = async () => {
  const data = await getSharedData()
  // 使用相同的数据,不会触发新的请求
  
  return (
    // ... component JSX
  )
}

这种方式的优点:

  • 数据获取逻辑集中管理,易于维护
  • 使用 cache 确保多个组件调用时只请求一次
  • 可以在 getSharedData.ts 中定义清晰的类型
  • 便于添加错误处理和数据转换逻辑

如果某些组件只需要部分数据,你也可以拆分成多个更小的缓存函数:

getSharedData.ts

javascript 复制代码
export const getAnchorArticleData = cache(async () => {
  return await getAnchorArticle()
})

export const getMaterialCategoryData = cache(async () => {
  return await getMaterialCategory()
})

export const getTechnologyCategoryData = cache(async () => {
  return await getTechnologyCategory()
})

这样组件可以只获取它们需要的数据:

javascript 复制代码
const SomeComponent = async () => {
  // 只获取需要的数据
  const anchorArticle = await getAnchorArticleData()
  
  return (
    // ... component JSX
  )
相关推荐
爱勇宝2 小时前
研究数字孪生的这半年,做了个 Demo,也有了一些新想法
前端·程序员
不可能片场2 小时前
工程实践 一个缓存把选片从十分钟压到一分钟
前端·electron
前端小万2 小时前
探索副业五个月,最终以放弃告终
前端·后端·面试
FRing032 小时前
JavaScript入门到精通二十四(正则表达式、元字符、修饰符)
开发语言·前端·javascript·正则表达式
葡萄城技术团队3 小时前
在 SpreadJS 里新增右键菜单,把业务动作放到用户手边
前端
大明二代3 小时前
从 RAG 到有记忆的 Agent:Mastra Memory 与 PostgreSQL 实战
前端·javascript·人工智能
deli0073 小时前
代码截图一键出 PNG 实测:3 种窗口风格,长行超 95 字符会被裁
前端
大哥43093 小时前
慢 ≠ 挂:AI 搜索降级判定的设计,与一次 reasoning 模型排查复盘
前端
UaoN3 小时前
作为全栈开发者,为什么看到 Shopify 回归原生,我依然选择 React Native
前端·后端
PBitW3 小时前
行内编辑,前端如何兜底?😭😭😭
前端·面试