首頁 > web前端 > js教程 > 主體

為什麼 React 的 `this.setState` 函數在 ComponentDidMount 回呼中不可用?

Linda Hamilton
發布: 2024-10-23 17:04:02
原創
337 人瀏覽過

Why is React's `this.setState` Function Unavailable in ComponentDidMount Callback?

「React this.setState 不是函數」問題:上下文綁定

嘗試使用第三方API 開發應用程式時,常見的錯誤是「TypeError: this.setState is not a function」。當嘗試處理 API 回應時會出現這種情況。這個問題通常源自於不正確的綁定。

提供的 React 程式碼使用 componentDidMount 方法定義了一個名為 AppMain 的元件。在此方法中,呼叫 VK API 來檢索使用者資訊。在 API 回應的回呼函數中,嘗試使用 this.setState 來更新元件的狀態。但是,出現錯誤是因為回呼函數是在不同的上下文中執行的,並且無法存取 this.setState。

解決方案:

要解決此問題,回調函數必須綁定到正確的上下文。這可以透過使用.bind 方法來實現:

VK.api('users.get', { fields: 'photo_50' }, function(data) {
  if (data.response) {
    this.setState({ // the error happens here
      FirstName: data.response[0].first_name
    });
    console.info(this.state.FirstName);
  }
}.bind(this));
登入後複製

透過將回調函數綁定到元件實例,回調函數中的this 關鍵字將引用元件實例,從而允許存取其方法和屬性,包括this.setState.

附加綁定:

在某些情況下,可能需要附加綁定。例如,如果在 componentDidMount 中也呼叫了 VK init 方法,則該方法也必須綁定到元件實例:

VK.init(function() {
  console.info("API initialisation successful");
  VK.api('users.get', { fields: 'photo_50' }, function(data) {
    if (data.response) {
      this.setState({ // the error happens here
        FirstName: data.response[0].first_name
      });
      console.info(this.state.FirstName);
    }
  }.bind(this));
}.bind(this), function() {
  console.info("API initialisation failed");
}, '5.34');
登入後複製

以上是為什麼 React 的 `this.setState` 函數在 ComponentDidMount 回呼中不可用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!