簡體   English   中英

盡管有箭頭功能,但在 axios 中未定義“this”

[英]“this” undefined in axios catch block despite arrow functions

我收到錯誤:

元素類型無效:應為字符串(用於內置組件)或類/函數(用於復合組件)但得到:未定義

使用此代碼:

class Registration extends React.Component {

  state = {...}

  submitRegistration = e => {
      let registration = {...}

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          this.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }

export default Registration;

問題是盡管我使用箭頭函數,但由於某種原因不能在 catch 塊中引用“this”。 我也嘗試過綁定“this”,但這也不起作用。 有人有想法嗎?

submitRegistration不應是箭頭 function。 通過使其成為箭頭 function,它沒有Registration class 實例的 scope。 將其更改為常規方法:


class Registration extends React.Component {

  state = {...}

  submitRegistration(e) {
      let registration = {...}

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          this.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }

export default Registration;

因為每個代碼塊中的“this”可能有不同的含義並引用其他父級。 為了解決這個問題,你必須在全局 scope 中定義一個變量並使其等於這個。 然后在代碼的 rest 中,該變量可能是可訪問的。

    class Registration extends React.Component {
       state = {...}
       submitRegistration = e => {
      let registration = {...}
      var sellf = this;

      Axios.post('/registration', registration)
        .then(res => {
          console.log("Successfully sent registration data", res)
        })
        .catch(() => {
          sellf.setState({ showNoServerConnectionAlert: true })
        });
    }
    e.preventDefault()
  }

  render() {
    return (
      ...
    )
  }
export default Registration;

暫無
暫無

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

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