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
  )
相关推荐
JudithHuang10 分钟前
React 常用 Hooks
前端·react.js·前端框架
sycmancia1 小时前
Qml——Window元素使用
前端
每天都好困1 小时前
03 AR 投影与误差修正:把地图上的点贴到视频画面上
前端
每天都好困1 小时前
04 地图图层封装:像管理 Photoshop 图层一样管理地图元素
前端
去伪存真2 小时前
构建你的第一个 DevOps AI Agent:自动化捕获、分析并修复 CI 故障
前端·agent
niucloud-admin2 小时前
JAVA V6 多商户商城 开发文档——手机端前端
java·开发语言·前端
喵个咪2 小时前
GoWind Admin|风行 — 开箱即用的企业级全栈中后台框架:脚本系统实战
javascript·后端·go
樱花落木兰2 小时前
SpringBoot + ECharts 后台数据统计报表模块实战
java·javascript·spring boot·ai·log4j·github·echarts
skywalk81632 小时前
deepseekharness在对话中,有四种模式,分别是极简、PTC、创造和标准模式,每种模式下挂载的插件、skill等数量不一样
前端·人工智能·实践
愛芳芳2 小时前
element-plus+vite+vue3+pinpa+mock+typeScript搭建经典的电商管理后台
前端·javascript·typescript