繁体   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