Why is this.context an empty object, in this React component lifecycle methods?
The context has the correct value in the Consumer for that context. Only the this.context API is failing.
const LoremContext = React.createContext({
lorem: "ipsum",
})
class MenuItem extends React.Component {
componentDidMount() {
console.log(
"In MenuItem.componentDidMount, this.context is:",
this.context)
}
render() {
console.log(
"In MenuItem.render, this.context is:",
this.context)
return ( <LoremContext.Consumer>{
(lorem) => {
console.log("In LoremContext.Consumer, lorem is:", lorem)
return (
<li>
{ `Eat ${this.props.dish} at ${lorem}` }
</li>
)
}
}</LoremContext.Consumer> )
}
}
MenuItem.contextType = LoremContext
class Menu extends React.Component {
render() {
…
}
}
class Application extends React.Component {
render() {
return (
<LoremContext.Provider value={ this.props.world.lorem }>
<section className="app">
<Menu menuItems={ [ … ] } />
<p>Fusce varius id arcu egestas sodales</p>
</section>
</LoremContext.Provider>
)
}
ReactDOM.render(
<Application world={ { lorem: "consecteur" } } />,
document.getElementById('app-container'),
)
This is using React 16.4, so it makes use of the documented context API (introduced in React 16.3).
According to that documented API, the above code should get access to the context (defined in the return value from React.createContext) in two ways:
The
LoremContext.Consumercomponent receives the context value passed by theLoremContext.Provider.The consumer then provides that context value as an argument to the function within that component. In this case,
loremis the argument that receives the context value.The
this.contextproperty receives (because of the declaredMenuItem.contextTypeclass property) the context value, inside the “lifecycle methods”.
Only one of those is working for me.
- The
LoremContext.ConsumerAPI is getting and passing the context value correctly. Theconsole.logoutput is:
In LoremContext.Consumer, lorem is: consecteur
- The
this.contextis not getting the correct value, instead it gets an empty Object. Theconsole.logoutput is:
In MenuItem.render, context is: Object { }
In MenuItem.componentDidMount, context is: Object { }
So the consumer is receiving the correct value, but this.context is not. Why the difference? How can I get the correct value received at this.context?