最佳答案
在 反应16关联文档页面上,他们有一些类似的例子:
const defaultValue = 'light'
const SomeContext = React.createContext(defaultValue)
const startingValue = 'light'
const App = () => (
<SomeContext.Provider theme={startingValue}>
Content
</SomeContext.Provider>
)
看起来 defaultValue
是无用的,因为如果您将 startingValue
设置为其他任何值或不设置它(即 undefined
) ,它将覆盖它。没关系,应该可以。
但是 defaultValue
有什么意义呢?
如果我想拥有一个不变的静态上下文,那么最好能够执行下面这样的操作,只需要通过 defaultValue
传递提供程序
const App = () => (
<SomeContext.Provider>
Content
</SomeContext.Provider>
)