问题:会发 4 次请求吗?(续)
// ✅ Next.js 做法:直接在每个组件请求
async function Layout() {
const user = await getCurrentUser(); // 第 1 次:真正请求
return (
<>
<Sidebar />
<Page />
</>
);
}
async function Sidebar() {
const user = await getCurrentUser(); // 第 2 次:复用第 1 次的结果
return <div>{user.name}</div>;
}
async function Page() {
const user = await getCurrentUser(); // 第 3 次:复用第 1 次的结果
return <UserProfile />;
}
async function UserProfile() {
const user = await getCurrentUser(); // 第 4 次:复用第 1 次的结果
return <div>{user.email}</div>;
}
优势:
- ✅ 代码简洁,每个组件独立获取数据
- ✅ 不需要 Prop Drilling
- ✅ 只发送 1 次真正的请求