this.props.history已被弃用(react router)

this.props.history is deprecated (react-router)

本文关键字:react router props history this      更新时间:2023-10-03

我试图用程序导航到另一个页面,就像this.props.history.push('/new-path');一样,它起作用了,但我在控制台中收到了一条弃用警告,说:

Warning: [react-router] props.history and context.history are deprecated. Please use context.router.点击此处了解更多信息https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#changes-到这个上下文


之后,我尝试像this.context.router.push('/new-path')一样使用这种新方法,但这似乎不是正确的方法。

也许您忘记将路由器定义为contextType?假设你有一个像这样的组件

class YourComponent extends React.Component {
      render() {
        return <div></div>;
      }
 }

您必须在组件下面定义如下contextTypes:

YourComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
};