简体   繁体   中英

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

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 });
  });

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 });
  });
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM