路由问题:尝试重路由时没有定义this.context.router

Routing issue: this.context.router not defined when trying to re-route

本文关键字:路由 定义 this router context 问题      更新时间:2023-09-26

我试图在n秒后自动更改路径。(不使用<Link to="/home">Home</Link>).

我的代码是这样的:

class ComponentName extends Component {
  constructor (props, context) {
    super(props, context);
  }
  componentDidMount () {
    setTimeout(function(){
      this.context.router.transitionTo('/home');
    }.bind(this), 3000)
  }
  render() {return (<div>..will go to the home page</div>)}
}
ComponentName.contextTypes = {
  router: function () { 
    return React.PropTypes.func.isRequired;
  }
};
export default ComponentName;

这是我得到的错误

Uncaught TypeError: Cannot read property 'transitionTo' of undefinedon line this.context.router.transitionTo('/home');又名this.context.router is undefined

。上下文是定义的,所以没有问题。

事情我尝试了以下一些:

  • 构造函数中:
  • this.context = context;
    

  • 在班上:
  • static contextTypes: {
      history: React.PropTypes.object,
      location: React.PropTypes.object,
      router: React.PropTypes.func.isRequired
    }
    

  • 在导出之前(尝试使用&没有函数):
  • ComponentName.contextTypes = {
      router: React.PropTypes.func.isRequired
    }
    

  • 我也试过改变历史路线,或者只是在上下文中调用函数:
  • this.context.history.transitionTo('/home');
    this.context.transitionTo('/home');
    this.transitionTo('/home');
    

    事实是this.context.router仍然未定义,我已经搜索了更多的线程(主要是这个:https://github.com/rackt/react-router/issues/975),仍然找不到适合我的东西。

    注意:我使用的是ES6 &

    "react": "^0.14.0",
    "react-router": "^1.0.0-rc3"
    

    已经有一个答案解释了如何以编程方式为每个react-router版本强制一个新路由:https://stackoverflow.com/a/31079244/5810646

    你是(或者我应该用"were")试图在你的页面上3秒后强制一个新的路由。这不应该是与历史记录相关的问题,因为您正在使用的react-router版本是1.0.0-rc3(顺便看看您的代码,它似乎不是)。

    如果你使用react-router 2.x.x:

    ,你可以利用历史推送一条新路由
    import { browserHistory } from 'react-router'
    

    然后做:

    browserHistory.push('/some/path')
    

    一种解决方案是在自己的文件中创建历史记录,并像这样导出:

    import createHistory from 'history/createHashHistory'
    export default createHistory()
    

    当你定义你的应用程序时,你这样做:

    import React from 'react'
    import { Provider } from 'react-redux'
    import { Router } from 'react-router-dom'
    import history from '../history'
    const Application = (props) => {
      return (
        <Provider store={props.store}>
          <Router history={history}>
            ...
          </Router> 
        </Provider>
      )
    }
    

    最后,当你需要访问任何组件中的历史记录时,只需从导出的同一个文件中导入它,以推送下一个路由。