All issue in the code:
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router'
export default class App extends Component {
// If use constructor below this.context is undefined,
// otherwise comment the constructor statement this.context not null
// Uncaught TypeError: Cannot read property 'router' of undefined
router = this.context.router;
constructor (props) {
super(props);
console.log(this);
}
render () {
return <span>ReactDemo</span>
}
static contextTypes = {
router: PropTypes.object.isRequired
};
}
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}/>
</Router>
), document.getElementById('root'));
The react versioin is 15.0.1,i remember a previous version without this problem.
Is this a bug or the usage of my problem?
Here is my demo git:
https://github.com/shenyzore/react-demo.git
Thanks!
you should pass the second param:
constructor(props, context) {
// context can be accessed now
}
@linzerui it works, thanks a lot!
Is this documented anywhere? I just went looking under https://facebook.github.io/react/docs/ but eventually got here via Google because I couldn't find it there...
@depoulo I think there is no document for this, but you can inspired by the usage of context-in-stateless-functional-components
Which is far from ideal, but thx anyway!
Update for 16.x: passing context to constructor is not documented in 'current' documentation, I did find it in the legacy-documentation though. This leads me to believe it is deprecated.
According to the new documentation in the section that links to the legacy-docs: "The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version." (Found here)
you should pass the second param:
constructor(props, context) { // context can be accessed now }
Thank you!
Most helpful comment
you should pass the second param: