首页 > 解决方案 > 反应路由器`this.props.history.push` - 历史未定义

问题描述

我有这个注销功能:

logOut = () => {
    axios
      .delete(`${apiUrl}/logout`)
      .then(response => {
        if (response.status === 204) {
          localStorage.removeItem('key', response.headers.authorization)
          localStorage.removeItem('id', response.data.id)
          // return <Redirect to="/login" />
          this.props.history.push(`/login`)
        }
      })
      .catch(error => {
        console.log(error)
      })
  }

this.props.history.push('/something')适用于其他场合。但这里它说无法读取push未定义。我试过return <Redirect to="/login" />哪个也不起作用。

我究竟做错了什么?

标签: reactjsreact-router

解决方案


这可能是由于以下原因之一:

1-使用history.push时需要将组件传递给withRouter:

    import { withRouter } from 'react-router-dom

   // ... codes of component in here ...

    export default withRouter(componentName) // at the end of component

2-是指 axios,您需要在 axios 上用另一个名称定义它并在 axios 中使用它,例如:

var that = this;

 // then use that in axios

推荐阅读