反应路由器`this.props.history.push`-历史未定义

Soo*_*ran 1 reactjs react-router

我有这个注销功能:

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)
      })
  }
Run Code Online (Sandbox Code Playgroud)

this.props.history.push('/something')在其他场合也可以工作。但是在这里它说无法读取push未定义。我尝试了return <Redirect to="/login" />那也不行。

我究竟做错了什么?

Pou*_*ani 9

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

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

    import { withRouter } from 'react-router-dom

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

    export default withRouter(componentName) // at the end of component
Run Code Online (Sandbox Code Playgroud)

2- 这是指axios,您需要使用其他名称在axios上定义此名称,并在axios中使用它,例如:

var that = this;

 // then use that in axios
Run Code Online (Sandbox Code Playgroud)