暂停
¥Suspense
在 SWR (More information) 等数据框架中仍然使用 Suspense
来响应 doesn't recommend。根据我们的研究结果,这些 API 将来可能会发生变化。
¥React still doesn't recommend using Suspense
in data frameworks like SWR (More information). These APIs may change in the future as the results of our research.
你可以启用 suspense
选项以将 SWR 与 React Suspense 结合使用:
¥You can enable the suspense
option to use SWR with React Suspense:
import { Suspense } from 'react'
import useSWR from 'swr'
function Profile () {
const { data } = useSWR('/api/user', fetcher, { suspense: true })
return <div>hello, {data.name}</div>
}
function App () {
return (
<Suspense fallback={<div>loading...</div>}>
<Profile/>
</Suspense>
)
}
请注意,suspense
选项在生命周期中不允许更改。
¥Note that the suspense
option is not allowed to change in the lifecycle.
在 Suspense 模式下,data
始终是获取响应(因此你不需要检查它是否是 undefined
)。但如果发生错误,则需要使用 错误边界 (opens in a new tab) 来捕获它:
¥In Suspense mode, data
is always the fetch response (so you don't need to check if it's undefined
).
But if an error occurred, you need to use an error boundary (opens in a new tab) to catch it:
<ErrorBoundary fallback={<h2>Could not fetch posts.</h2>}>
<Suspense fallback={<h1>Loading posts...</h1>}>
<Profile />
</Suspense>
</ErrorBoundary>
Suspense 模式会暂停渲染,直到数据准备好,这意味着它很容易导致瀑布问题。为了避免这种情况,你应该在渲染之前预请求资源。更多信息
¥Suspense mode suspends rendering until the data is ready, which means it causes waterfall problems easily. To avoid that, you should prefetch resources before rendering. More information
注意:使用条件请求
¥Note: With Conditional Fetching
通常,当你启用 suspense
时,可以保证 data
在渲染时始终准备就绪:
¥Normally, when you enabled suspense
it's guaranteed that data
will always be ready on render:
function Profile () {
const { data } = useSWR('/api/user', fetcher, { suspense: true })
// `data` will never be `undefined`
// ...
}
然而,当它与条件获取或依赖获取一起使用时,如果请求暂停,data
将是 undefined
:
¥However, when using it together with conditional fetching or dependent fetching, data
will be undefined
if the request is paused:
function Profile () {
const { data } = useSWR(isReady ? '/api/user' : null, fetcher, { suspense: true })
// `data` will be `undefined` if `isReady` is false
// ...
}
如果你想了解有关此限制的更多技术细节,请查看 这里的讨论 (opens in a new tab)。
¥If you want to read more technical details about this restriction, check the discussion here (opens in a new tab).
服务器端渲染
¥Server-Side Rendering
在服务器端使用 Suspense 模式时(包括 Next.js 中的预渲染),需要通过 回退数据或回退 提供初始数据。这意味着你不能使用 Suspense
在服务器端获取数据,而是要么完全进行客户端数据请求,要么通过框架级数据请求方法(例如 Next.js 中的 getStaticProps)获取数据。更多讨论可以参见 此处 (opens in a new tab)。
¥When using suspense mode on the server-side (including pre-rendering in Next.js), it's required to provide the initial data via fallbackData or fallback. This means that you can't use Suspense
to fetch data on the server side, but either doing fully client-side data fetching, or fetch the data via the framework level data fetching method(such as getStaticProps in Next.js). More discussions can be found here (opens in a new tab).