Ryan Toronto瑞安·多伦多
React's cache() memoizes your function calls when rendering server components.
React 的 cache() 会在渲染服务器组件时记住您的函数调用。
This short-lived cache is useful when you are fetching data in multiple places, for example a layout and a page that both fetch the current user.
当您在多个位置获取数据时,例如同时获取当前用户的布局和页面,这种短暂的缓存非常有用。
One of the problems with co-locating data fetching and rendering in async components is that these components are now blocked while they’re fetching data.
在异步组件中共同定位数据获取和渲染的问题之一是这些组件在获取数据时被阻塞。
For example, all your components that fetch the current user are now on the hook for that network latency.
例如,所有获取当前用户的组件现在都受到网络延迟的影响。
In client React we have context and module-scoped external stores to manage loading states and shared fetches, but in RSC we don’t have access to those tools.
在客户端 React 中,我们有上下文和模块范围的外部存储来管理加载状态和共享获取,但在 RSC 中我们无法访问这些工具。
- No context because no re-renders
没有上下文,因为没有重新渲染 - No external stores because module scope is shared by multiple requests
没有外部存储,因为模块范围由多个请求共享
This is where cache comes in: it gives us a place to stash data, on a per request basis, while rendering RSCs:
这就是 cache 的用武之地:它为我们提供了一个在渲染 RSC 时根据每个请求存储数据的地方:
import { cache } from "react";
export default async function Page() {
let article = await getTopArticle();
return (
<div>
The top article is {article.title}
<Again />
<Again />
<Again />
</div>
);
}
async function Again() {
let article = await getTopArticle();
return <div>Again, it's {article.title}</div>;
}
// This function is called in four places,
// but it will only run once!
let getTopArticle = cache(async () => {
return db.query("select * from articles...");
});
In this example, after one component fetches the top article, all other components that need the article will re-use the result of the first fetch. React only makes one database query even though multiple components are calling getTopArticle().
在此示例中,在一个组件获取顶部文章后,需要该文章的所有其他组件将重新使用第一次获取的结果。即使多个组件正在调用 getTopArticle() ,React 也只会进行一次数据库查询。
Dig deeper深入挖掘
Last updated:最近更新时间:

