【发布时间】:2019-08-16 03:23:23
【问题描述】:
我正在尝试使用 Context API 根据用户的登录状态来呈现 UI 组件。 Context.Consumer 似乎从 Context.Provider 获取值,但该值存储在 1 的键上,而 Consumer 的子函数正在从 0 或 _currentValue 获取值。
如何让消费者使用新提供的值而不是默认值?
一些简化的代码 sn-ps...
<Layout /> 包裹所有页面,<MenuContent /> 在 <body /> 内部呈现
const { Provider, Consumer } = React.createContext("defaultValue");
function Layout() {
return (
<Provider value="newValue">
<body>{props.body}</body>
</Provider>
);
}
function MenuContent() {
console.log('ConsumerObject:', Consumer);
return(
<Consumer>
{ value => console.log("value:", value) }
</Consumer>
);
}
控制台打印:
value: "defaultValue"
和
ConsumerObject: {
'$$typeof': Symbol(react.context),
_context: {
'0': 'defaultValue',
'1': 'newValue',
'$$typeof': Symbol(react.context),
_calculateChangedBits: null,
_currentValue: 'defaultValue',
_currentValue2: 'defaultValue',
_threadCount: 2,
Provider: { '$$typeof': Symbol(react.provider), _context: [Circular] },
Consumer: [Circular],
_currentRenderer: null,
_currentRenderer2: null
},
_calculateChangedBits: null
}
所以,我看到 newValue 位于 Consumer 对象上,但它似乎不在正确的位置,无法按照文档所示访问它。
希望我解释得足够好...提前致谢。
【问题讨论】:
标签: reactjs