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.Consumer
component 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,
lorem
is the argument that receives the context value.The
this.context
property receives (because of the declaredMenuItem.contextType
class property) the context value, inside the “lifecycle methods”.
Only one of those is working for me.
- The
LoremContext.Consumer
API is getting and passing the context value correctly. Theconsole.log
output is:
In LoremContext.Consumer, lorem is: consecteur
- The
this.context
is not getting the correct value, instead it gets an empty Object. Theconsole.log
output 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
?