this.props.history 已弃用(反应路由器)

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

我试图以编程方式导航到另一个页面,就像这样 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-to-thiscontext


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

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

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

您必须在组件下方按如下方式定义 contextTypes:

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