如何使用"this"提取API调用结果中的关键字 [英] How to use "this" keyword inside a fetch API call result
本文介绍了如何使用"this"提取API调用结果中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下提取API来获取API结果.我需要将结果数据设置为状态,但是回调函数中无法使用"this"对象.如何通过访问this
关键字来更新代码以将值设置为状态?
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 });
});
推荐答案
- 将
this
关键字分配给仍可使用的回调之外的变量.通常使用var self = this;
. - 在需要的回调中使用"self".
- Assign
this
keyword 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.
这篇关于如何使用"this"提取API调用结果中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文