React中路由跳转报错:Cannot read property ‘push’ of undefined

1,175 阅读1分钟

React中路由跳转报错:

页面在Router中配置了,但组件无法使用 this.props.history.push() 进行跳转,并且会出现报错:Cannot read property ‘push’ of undefined 得到 push of undefined 的报错因是为组件并没有使用 history 的能力

解决方案:

1)给组件添加路由
//引入withRouter
import {withRouter} from 'react-router-dom'

class Subject extends Component {
  ...
}
  
// 关键一步:通过withRouter导出组件
export default withRouter(Subject)
2)将配置过路由的父级的history传给该组件,即可在该组件使用history跳转
// 父组件中:
<Subject history={this.props.history} />