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)