全书目录

第三十五篇:Astro 完全指南 —— 内容展馆群岛宇宙

第二十章:Server Islands,是“整馆先开,再单独补上个性化展台”

1 分钟 285 字 第 672 / 962 个阅读单元

Astro 岛屿架构里,很多人只记住了 client islands。
但到了更完整的项目里,server islands 也非常重要。

它解决的是这种场景:

  • 整页内容大多可提前渲染
  • 只有一小块需要请求期服务器数据
  • 而且你不想让这小块阻塞整页

比如:

  • 登录用户头像
  • 个性化推荐卡片
  • 购物车摘要
  • A/B 测试插槽
  • 实时库存小组件

典型写法:

astro
---
import PersonalizedPanel from '../components/PersonalizedPanel.astro';
---

<h1>本周特展</h1>
<p>这部分内容可以立刻开馆。</p>

<PersonalizedPanel server:defer userId="current-user">
  <p slot="fallback">正在为你准备个性化导览...</p>
</PersonalizedPanel>

组件本体:

astro
---
// src/components/PersonalizedPanel.astro
const { userId } = Astro.props;
const profile = await getVisitorProfile(userId);
---

<section>
  <h2>你的专属导览</h2>
  <p>欢迎回来,{profile.name}</p>
  <p>你上次停留在 {profile.lastHall} 展厅。</p>
</section>

这背后的机制可以这样记:

text
页面主展馆先打开
server:defer 区域被拆成单独后补的服务端小岛
fallback 先顶上
真正内容随后补到位

这特别适合“95% 是公开内容,5% 是个性化”的页面。

但也要记住两个边界:

  • server:defer 需要 adapter
  • 传给 server island 的 props 必须可序列化