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

心不动则不痛 提交于 2019-12-12 19:19:32

问题


I'm using the following fetch API to get an API result. I need to set the result data in the state but the "this" object is unavailable inside the callback function. How can I update the code to set the value in the state by accessing the this keyword?

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

回答1:


  • Assign this keyword to a variable that's outside the callback where it is still available. Often var self = this; is used.
  • Use 'self' in the callback where you need it.



回答2:


You can use arrow functions

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

or you can assign the this keyword to a variable and use that like 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 });
  });


来源:https://stackoverflow.com/questions/50523225/how-to-use-this-keyword-inside-a-fetch-api-call-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!