折腾:
期间,对于代码:submitLogin(e){
//TODO: call API to login
console.log(‘Login submitLogin’);
stopEventPropgation(e);
console.log(e);
console.log(this);
console.log(this.context);
console.log(this.context.router);
// this.context.router.push(‘/main’);
}
结果:Login {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}
login.js:66 {}
undefined
即:
react js react-router this.context.router empty
react js this.context.router empty
react js this.context.router undefined
试试:
context.history
结果
console.log(this.context.history);
也是undefined
我此处版本是最新的稳定的:"react-router": "^4.1.2",
"react-router-dom": "^4.1.2",
所以看来不是版问题。
加上:
contextTypes: {
router: PropTypes.object
},
试试。
【总结】
先去安装prop-types:➜ rse_web git:(master) ✗ npm install prop-types
npm WARN babel-loader@6.2.10 requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN react-dom@15.6.1 requires a peer of react@^15.6.1 but none was installed.
removed 2 packages and updated 1 package in 9.269s
再用代码:import PropTypes from ‘prop-types’;
export default class Login extends Component {
state = {
};
submitLogin(e){
//TODO: call API to login
console.log(‘Login submitLogin’);
stopEventPropgation(e);
console.log(e);
console.log(this);
console.log(this.context);
console.log(this.context.router);
// console.log(this.context.history);
if (this.context.router) {
this.context.router.push(‘/main’);
}
}
…
}
Login.contextTypes = {
router: PropTypes.object.isRequired
};
结果好像就可以了:
【后记1】
后来看到官网:
Context – React
中有详细的解释了:
如果没有定义contextTypes,则context是个空的对象{}
如果定义了contextTypes,后续才能使用context。
-》才能通过context去获得对应的router
即:this.context.router