在React 16 Context doc页面上,它们具有类似于以下示例:
const defaultValue = 'light'; const SomeContext = React.createContext(defaultValue); const startingValue = 'light'; const App = () => ( <SomeContext.Provider theme={startingValue}> Content </SomeContext.Provider> )
似乎defaultValue是无用的,因为如果您改为将设置startingValue为其他值或未设置(为undefined),则它将覆盖它。很好,应该这样做。
startingValue
undefined
但是,那有什么意义defaultValue呢?
defaultValue
如果我想拥有一个不变的静态上下文,那么能够执行以下操作,并让Provider通过 defaultValue
const App = () => ( <SomeContext.Provider> Content </SomeContext.Provider> )
如果没有提供者,则defaultValue参数用于函数createContext。这对于隔离测试组件而不包装它们或使用Provider提供的不同值进行测试很有帮助。