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