问题
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
thiskeyword to a variable that's outside the callback where it is still available. Oftenvar 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