[英]How can I suspend component on the server side but render it on the client side?
Is there a way to keep the component suspended on the server side and render it on the client with React 18?有没有办法让组件在服务器端保持暂停状态,并使用 React 18 在客户端渲染它? I tried using this pattern https://beta.reactjs.org/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content .我尝试使用这种模式https://beta.reactjs.org/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content 。 It works as expected but the problem is that if I use this pattern in multiple components the console gets filled with errors that were thrown on the server side by the component so it would remain suspended.它按预期工作,但问题是如果我在多个组件中使用此模式,控制台将充满组件在服务器端抛出的错误,因此它将保持暂停状态。 Also later all these errors get passed to the client side稍后所有这些错误都会传递给客户端
<Suspense fallback={<Loading />}>
<Chat />
</Suspense>
function Chat() {
if (typeof window === 'undefined') {
throw Error('Chat should only render on the client.');
}
// ...
}
Server-side error:服务器端错误:
Error: Chat should only render on the client.",
"at Chat (/Users/Chat.tsx:86:19)
Client-side error:客户端错误:
Uncaught Error: Chat should only render on the client.
at updateDehydratedSuspenseComponent (react-dom.development.js:20662:1)
at updateSuspenseComponent (react-dom.development.js:20362:1)
at beginWork (react-dom.development.js:21624:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25738:1)
at workLoop (scheduler.development.js:266:1)
at flushWork (scheduler.development.js:239:1)
Is there a way to achieve the same functionality but prevent errors to appear in the console without third-party SSR libraries like Next.js?有没有办法在没有像 Next.js 这样的第三方 SSR 库的情况下实现相同的功能但防止错误出现在控制台中? My project uses the express and react-dom/server to do the SSR.我的项目使用 express 和 react-dom/server 来做 SSR。
If you're using Next.js for SSR you can mark the component for CSR with 'use client';
如果您将 Next.js 用于 SSR,则可以将 CSR 组件标记为'use client';
at the top of the file, see these Server and Client Components docs.在文件的顶部,请参阅这些服务器和客户端组件文档。
Suspense is simply a fallback for asynchronous rendering but will still render on the server, as far as I know.据我所知,Suspense 只是异步渲染的后备,但仍会在服务器上渲染。
Workaround with useEffect
:使用useEffect
的解决方法:
function Wrapper() {
const [client, setClient] = useState(false)
useEffect(() => {
setClient(true)
}, [])
if (!client) return null
return <Chat />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.