简体   繁体   English

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

[英]React router `this.props.history.push` - history not defined

I have this logout function: 我有这个注销功能:

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') works on every other occasion. this.props.history.push('/something')在其他场合也可以使用。 But here it says cannot read push of undefined. 但是在这里它说无法读取未定义的push I tried return <Redirect to="/login" /> which doesn't work too. 我尝试return <Redirect to="/login" /> ,它也不起作用。

What am I doing wrong? 我究竟做错了什么?

It may because of one of these reasons: 可能是由于以下原因之一:

1- You need to pass your component to withRouter when you are using history.push: 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- this is referring to axios and you need to define this over the axios with another name and use it in axios eg: 2- 是指axios,您需要使用其他名称在axios上定义此名称,并在axios中使用它,例如:

var that = this;

 // then use that in axios

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM