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 });
});
this
keyword to a variable that's outside the callback where it is still available. Often var self = this;
is used.
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.