2 回答

TA贡献1784条经验 获得超9个赞
SampleContext将您的文件更改为:
import React from 'react';
const SampleContext = React.createContext();
const SampleContextProvider = ({children}) => {
return (
<SampleContext.Provider value={{a: 'a', b: 'b'}}>
{children}
</SampleContext.Provider>
);
};
export {SampleContext, SampleContextProvider};
我在提供者值道具中定义了您的默认上下文值,而不是作为createContext.
提供者的 value 属性会覆盖在createContext. 这意味着如果您不设置value是否使用提供程序,则默认值将覆盖为未定义。

TA贡献1780条经验 获得超5个赞
在您的欢迎屏幕中尝试执行此操作
import {SampleContext} from '../provider/SampleContext';
const {a,b}= useContext(SampleContext);
console.log("contextx=> ", a+' '+b);
我认为解构该值可能会帮助您确认 sampleContext 是否具有上下文值!
添加回答
举报