React 上下文是否应该始终是单例,还是有其他方法?

Lan*_*ard 5 reactjs react-context

我见过的React上下文的每个例子都是这样

theme-context.js

// Make sure the shape of the default value passed to
// createContext matches the shape that the consumers expect!
export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});
Run Code Online (Sandbox Code Playgroud)

您的文件包含上下文的实例。然后使用将其传递到组件中useContext(ThemeContext)

我的问题是,如果你这样做并且它始终是单例,那么为什么不直接从单例导入上下文中的内容呢?基本上我想知道是否有一次您创建了多个上下文实例,例如为了测试,您可能会在每次测试时创建一个新实例,类似的事情。

小智 -3

首先, 中的值React.createContext({'light'})是默认值。它主要用于调试或跳过它,并将其留空React.createContext()。使用示例:您的 Context.Provider 中有一个数据,但您不确定是否将其正确传递给您的Product.Consumer,因此如果弹出默认值,您就知道您做错了什么。

在文档中,这种技术用于传递简单数据,例如 singletone React.createContext({'theme:themes.dark'})

大多数情况下,您将使用Context.Providerand Context.Consumer,甚至通过this.context

文档严格解释了每个细节,请尝试在文档中搜索Context.Provider, Class.contextType, Context.Consumer