概览`use` 允许在服务器组件中直接消费 Promise,配合 Suspense 可在数据就绪前渲染占位并以流式填充。错误边界则保障失败时的可恢复性与清晰反馈。服务器组件数据获取// app/posts/[id]/Post.tsx

export default function Post({ id }: { id: string }) {

const p = fetch(`https://api.example.com/posts/${id}`, { next: { revalidate: 300, tags: ['posts'] } }).then(r => r.json())

const data = use(p)

return <article><h1>{data.title}</h1><p>{data.body}</p></article>

}

Suspense 包裹// app/posts/[id]/page.tsx

import { Suspense } from 'react'

export default function Page({ params }: { params: { id: string } }) {

return (

<Suspense fallback={<p>加载中…</p>}>

{/* @ts-expect-error RSC */}

<Post id={params.id} />

</Suspense>

)

}

错误边界// app/posts/[id]/error.tsx

'use client'

export default function Error({ error, reset }: { error: Error; reset: () => void }) {

return (

<div role="alert">

<p>加载失败:{error.message}</p>

<button onClick={reset}>重试</button>

</div>

)

}

治理要点在服务器组件中优先使用 `use` 简化数据获取;必要时在客户端组件中保留传统 `useEffect` 路径。使用 `tags/revalidate` 管理缓存与失效,避免重复渲染。将关键区块包裹在 Suspense,提供骨架与流式体验;错误边界保障失败可恢复。验证与指标React:19.0+;Next.js:15.0+首屏与数据区块流式填充稳定;失败场景可重试并恢复

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部