最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ReactJS中react-router的this.context.router未定义

ReactJS crifan 4498浏览 0评论

折腾:

【已解决】React中合并login.html和index.html成单个app.js

期间,对于代码:

  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

this.context.router is undefined · Issue #975 · ReactTraining/react-router

this.context.router is undefined in ES6 class constructor · Issue #1059 · ReactTraining/react-router

reactjs – Why is my context.router undefined in my react component? – Stack Overflow

reactjs – How does React Router get into the React context? – Stack Overflow

This.context.router undefined · Issue #343 · reactjs/react-router-redux

The context router undefined · Issue #4645 · ReactTraining/react-router

试试:

context.history

结果

    console.log(this.context.history);

也是undefined

我此处版本是最新的稳定的:

    "react-router": "^4.1.2",
    "react-router-dom": "^4.1.2",

所以看来不是版问题。

加上:

  contextTypes: {

    router: PropTypes.object

  },

试试。

javascript – Routing issue: this.context.router not defined when trying to re-route – Stack Overflow

javascript – Can’t access context.router with react-router-redux – Stack Overflow

javascript – react and react-router context undefined – Stack Overflow

【总结】

先去安装prop-types:

➜  rse_web git:(master) ✗ npm install prop-types
npm WARN [email protected] requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN [email protected] 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

https://facebook.github.io/react/docs/context

中有详细的解释了:

如果没有定义contextTypes,则context是个空的对象{}

如果定义了contextTypes,后续才能使用context。

-》才能通过context去获得对应的router

即:this.context.router

转载请注明:在路上 » 【已解决】ReactJS中react-router的this.context.router未定义

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.176 seconds, using 22.12MB memory