簡體   English   中英

如何在提取API調用結果中使用“ this”關鍵字

[英]How to use “this” keyword inside a fetch API call result

我正在使用以下提取API來獲取API結果。 我需要將結果數據設置為狀態,但是回調函數中無法使用“ this”對象。 如何通過訪問this關鍵字更新代碼以將值設置為狀態?

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(function(res) {
    return res.json();
  })
  .then(function(data) {
    this.setState({ id: data.id });
  });

您可以使用箭頭功能

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(res => {
    return res.json();
  })
  .then(data => {
    this.setState({ id: data.id });
  });

或者,您可以將this關鍵字分配給變量,然后像var that = this;使用它var that = this;

fetch(config.apiUrl + '/api/user', {
  headers: authHeader(),
  method: 'GET',
})
  .then(function(res) {
    return res.json();
  })
  .then(function(data) {
    that.setState({ id: data.id });
  });
  • this關鍵字分配給仍在回調之外的變量。 通常var self = this; 用來。
  • 在需要的回調中使用“ self”。

暫無
暫無

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

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