【发布时间】:2020-06-24 21:55:16
【问题描述】:
我一直在关注一些 React Hooks 教程以使用 useContext。
在父组件中,我创建了一个新的上下文,
export const Context = createContext({fakeData: 'fake'})
然后在其中一个子组件中,我尝试通过这样做来访问这些数据,
console.log('fakeData1', useContext(Context))
const context = useContext(Context)
console.log('fakeData2', context)
然后我从父组件导入Context。
在我的console.log 中,fakeData2 给了我未定义,但fakeData1 给了我
{$$typeof: Symbol(react.context), _calculateChangedBits: null, _currentValue: undefined, _currentValue2: {…}, _threadCount: 0, …}
$$typeof: Symbol(react.context)
Consumer: {$$typeof: Symbol(react.context), _context: {…}, _calculateChangedBits: null, …}
Provider:
$$typeof: Symbol(react.provider)
_context: {$$typeof: Symbol(react.context), _calculateChangedBits: null, _currentValue: {…}, _currentValue2: {…}, _threadCount: 0, …}
__proto__: Object
_calculateChangedBits: null
_currentRenderer: {}
_currentRenderer2: null
_currentValue: {fakeData: "fake"}
_currentValue2: {fakeData: "fake"}
_threadCount: 0
__proto__: Object
由于Context中有数据,我假设导入成功,但不知道为什么不能直接通过
const context = useContext(Context)
console.log('fakeData2', context)
我假设这个对象有一个名为 fakeData 的字段,但事实并非如此。
有什么帮助吗?
【问题讨论】:
-
const {fakeData} = useContext(Context)能提供您想要的东西吗? -
这是我所期望的,但事实并非如此。
Context对象没有名为fakeData的字段 -
我注意到一个奇怪的行为,在
createContext中设置默认值会直接导致未定义的行为。尝试在提供程序的value属性中对其进行初始化,并将createContext的参数留空 -
你是说像
export const Context = createContext()一样清空Context的参数吗?这也没有奏效。它给了我同样的结果 -
查看Codesandbox,它显示了一个工作示例。但是,如果您从
Context.Provider组件中删除value属性,而是将默认值放在对createContext的调用中,则会导致您描述的未定义行为
标签: reactjs react-hooks react-context