【问题标题】:Is React context supposed to always be a singleton, or is there another way?React 上下文是否应该始终是单例,还是有其他方法?
【发布时间】:2019-11-29 02:03:28
【问题描述】:

我看到的关于React 上下文的每个示例都类似于this

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: () => {},
});

文件所在的位置包含上下文的实例。然后使用useContext(ThemeContext) 将其传递给组件。

我的问题是,如果您正在这样做并且它始终是单例,那么您为什么不直接从单例中直接导入上下文中的内容。基本上,我想知道是否曾经有过创建多个上下文实例的情况,例如可能为了测试,您为每个测试创建一个新实例,诸如此类。

【问题讨论】:

    标签: reactjs react-context


    【解决方案1】:

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

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

    在大多数情况下,你会使用Context.ProviderContext.Consumer,甚至通过this.context

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 2022-03-07
      • 1970-01-01
      • 2016-02-16
      • 2021-05-16
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      相关资源
      最近更新 更多