首页 > 解决方案 > React:如何在应用程序中的功能中重定向?

问题描述

我在应用程序(与路由器相同级别)中有一个注销功能,该功能被传递到各个页面,因此用户可以从任何地方注销。调用函数时如何添加重定向?

我尝试使用this.props.history.push("/");但得到错误Cannot read property 'push' of undefined

标签: reactjs

解决方案


使用 ( withRouter) 高阶组件

样本

import React from "react";
import { withRouter } from "react-router-dom";

class App extends React.Component {
  ...
  handleSubmit=()=>{
    this.props.history.push("/path");
  }
  ...
}
export default withRouter(App);

带有示例代码的现场演示


推荐阅读