react项目中引入了redux后js控制路由跳转方案

如果你的项目中并没有用到redux,那本文你可以忽略

问题引入

纯粹的单页面react应用中,通过this.props.history.push(‘/list’)就可以进行路由跳转,但是加上了redux后,使用这个语句并不能生效。相信你在做的过程也遇到了此问题,控制台报错了-_-

1
Uncaught TypeError: Cannot read property 'push' of undefined

解决方案

  1. 在将要使用js控制路由的组件中引入withRouter方法;

    1
    import { withRouter} from 'react-router-dom';
  2. 导出类的时候运用该方法

    1
    export default withRouter(MailListLeft)
  3. 在MailListLeft组件中正常使用 this.props.history.push(‘/list’)

    1
    <button type="button" onClick={()=>{this.props.history.push("/list");}}>去列表页面</button>