不是通过路由切换过来的组件中,如何在props中获取history

    科技2025-09-03  22

    withRouter作用
    首先,我们需要知道withRouter作用,把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上。在下边例子中如果不通过withRouter函数props中没有history对象。
    withRouter使用方式:

    首先要引入

    import { withRouter } from 'react-router-dom';

    将不是通过路由切换过来的组件,但是又需要获取history对象组件通过withRouter包裹。

    withRouter(组件名)

    由于我项目中使用dvajs来调用接口,所以,用connect连接一下,将props中传入dispatch函数。

    import React from 'react'; import { withRouter } from 'react-router-dom'; import notification from 'utils/notification'; import { connect } from 'dva'; function ProductionMonitoringDashboard(props) { function handleGoHome() { const { history } = props; history.push('/'); } return ( <div> <div> <div> <div className={styles['title-block']}> <img src={logoLeft} alt="logo-left" className={styles['logo-left']} /> <span style={{ cursor: 'pointer' }} onClick={handleGoHome}> 看板标题 </span> {timeComponent} <img src={logoRight} alt="logo-right" className={styles['logo-right']} /> </div> <div className={styles['announcement-block']}> <div> <img alt="announcement" /> <span>产线动态:欢迎校领导莅临指导</span> </div> </div> </div> </div> </div> ); } export default connect()(withRouter(ProductionMonitoringDashboard));

    到此组件中能够获取到history对象。

    Processed: 0.010, SQL: 9