簡體   English   中英

反應路由器`this.props.history.push`-歷史未定義

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

我有這個注銷功能:

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" /> ,它也不起作用。

我究竟做錯了什么?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM