React 上下文应该始终是单例,还是有另一种方式? [英] Is React context supposed to always be a singleton, or is there another way?
问题描述
我见过的关于 React
上下文的每个例子都像 this一个>:
Every example I've seen of React
context is like 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)
将其传递到组件中.
Where you're having a file contain an instance of the context. Then you pass it into the component using useContext(ThemeContext)
.
我的问题是,如果你正在这样做并且它总是一个单例,你为什么不直接从单例导入上下文中的内容,可以这么说.基本上,我想知道是否曾经有过创建多个上下文实例的情况,例如为了测试,您可能会为每个测试创建一个新实例,诸如此类.
My question is, if you're doing this and it's always a singleton, why don't you simply just import the stuff in the context directly from the singleton so to speak. Basically I'm wondering if there is ever a time where you create more than one instance of your context, such as perhaps for testing you create a new one per test, something like that.
推荐答案
首先,React.createContext({'light'})
中的值是默认值.它主要用于调试或只是跳过它,并将其留空 React.createContext()
.用法示例:您的 Context.Provider 中有一个数据,但您不确定是否将其正确传递给您的 Product.Consumer
,因此如果弹出默认值,您就知道您做错了什么.
First of all, the value in React.createContext({'light'})
is default.
It is mostly used for debug or just skip it, and leave it empty React.createContext()
.
Example of usage:
You have a data in your Context.Provider, but you are not sure, if you passed it right to your Product.Consumer
, so if the default value pops out, you know that you did something wrong.
在文档中,这种技术用于传递简单的数据,例如单音React.createContext({'theme:themes.dark'})
.
In documention such technique is used to pass simple data, like singletone React.createContext({'theme:themes.dark'})
.
在大多数情况下,您将使用Context.Provider
和Context.Consumer
,甚至通过this.context
.
In most cases, you will use Context.Provider
and Context.Consumer
, or even pass through this.context
.
文档严格解释了每一个细节,尝试在文档中搜索Context.Provider, Class.contextType, Context.Consumer
.
Documentation strictly explained every details, try search for Context.Provider, Class.contextType, Context.Consumer
in documentation.
这篇关于React 上下文应该始终是单例,还是有另一种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!