react 16.x中this.props找不到history

337 阅读1分钟

问题描述: 在react16.2.0中使用this.props.push改变路由的时候,一直报如下错误:

Cannot read properties of undefined (reading 'push')

先解决这个跳转的问题~

打印了一下this.props ,确实没有history属性,,,,

React 中,只有在 <Route> 包裹的组件中,才能在 this.props 属性中找到 history

我这边的解决方案是:

@withRouter
class Index extends Component {
    ...
}

这样再次打印this.props中就有history属性了~

此时,如果有在父组建里面引用子组建,需要再额外的传一个参数哦~

 render() {
      return (
        // 注意这个push参数哦~
      <ChildComponent push={this.props.history.push}/>
      )
  }

现在可以正常使用this.props.history.push('xxx')