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

【已解决】ReactJS中Uncaught TypeError this.context.router.push is not a function

ReactJS crifan 3996浏览 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);
    // console.log(this.context.history);
    if (this.context.router) {
      this.context.router.push(‘/main’);
    }
  }

但是

this.context.router.push(‘/main’);

报错:

Uncaught TypeError: this.context.router.push is not a function
    at Login.submitLogin (login.js:74)
    at Login.submitLogin (createPrototypeProxy.js:44)
    at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:70)
    at executeDispatch (EventPluginUtils.js:85)
    at Object.executeDispatchesInOrder (EventPluginUtils.js:108)
    at executeDispatchesAndRelease (EventPluginHub.js:43)
    at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54)
    at Array.forEach (<anonymous>)
    at forEachAccumulated (forEachAccumulated.js:24)
    at Object.processEventQueue (EventPluginHub.js:230)

Uncaught TypeError this.context.router.push is not a function

reactjs – this.context.router.push is not working – Stack Overflow

说是react-router v4是:

this.context.router.history.push(xxx)

这和自己调试期间看到的:

是一致的。

javascript – Uncaught (in promise) TypeError: _this2.context.router.push is not a function – Stack Overflow

transitionTo is not a function · Issue #1717 · ReactTraining/react-router

Uncaught TypeError: Cannot read property ‘push’ of undefined · Issue #3225 · ReactTraining/react-router

Uncaught TypeError: _gaReactRouter2.default.push is not a function · Issue #9 · tcoopman/ga-react-router

javascript – Uncaught TypeError: this.context.router.push is not a function – Stack Overflow

【总结】

去改为:

    if (this.context.router) {
      this.context.router.history.push(‘/main’);
    }

然后就可以了。

【后记】

后来看到:

reactjs – Navigating Programatically in React-Router v4 – Stack Overflow

以为react-router v4中,以代码方式手动跳转页面,也可以用:

this.context.router.transitionTo(e.target.href);

试的结果是:this.context.router.transitionTo是undefined

另外,以为:

this.context.router.history.go是可以跳转页面呢,结果无效,页面刷新了,但是还是当前页面。

转载请注明:在路上 » 【已解决】ReactJS中Uncaught TypeError this.context.router.push is not a function

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.211 seconds, using 22.14MB memory