相关疑难解决方法(0)

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

我见过的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)

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

reactjs react-context

5
推荐指数
1
解决办法
3152
查看次数

标签 统计

react-context ×1

reactjs ×1