在Next.js 13服务端组件中使用React.Context的问题求助
问题
Next.js 13已于一周前发布,我正尝试将一个Next.js 12应用迁移至Next.js 13。我希望尽可能多地使用服务端组件,但发现无法在任何服务端组件中使用import { createContext } from 'react';,会出现如下错误:
Server Error Error: You're importing a component that needs createContext. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default. ,---- 1 | import { createContext } from 'react'; : ^^^^^^^^^^^^^ `---- Maybe one of these should be marked as a client entry with "use client":
请问是否有替代方案,还是我必须通过属性透传来实现服务端渲染?
解决方案
- 将Context相关逻辑隔离到客户端组件:React Context API本身依赖客户端运行时,只能在标记了
'use client'的组件中使用。你可以把createContext、Context Provider以及消费Context的代码都放到客户端组件里,服务端组件作为子组件嵌套在Provider内部,通过Props接收所需数据,或者由客户端组件消费Context后再传递给服务端组件。 - 不必完全依赖属性透传:如果不想层层传递Props,可以在客户端组件中封装Context消费逻辑,把处理好的数据通过Props传递给下层的服务端组件。服务端组件依然可以保持纯服务端渲染特性,只负责接收数据并渲染UI。
- 服务端数据+客户端Context结合方案:如果Context原本用于传递服务端获取的数据,可以在服务端组件中直接获取数据,再通过Props传递给客户端组件的Provider,由客户端组件通过Context分发。这样既利用了服务端组件的数据获取优势,又能在客户端用Context管理状态。
内容的提问来源于stack exchange,提问作者Tomer Almog
相关产品推荐
相关产品推荐

