如何在fetch API调用的回调函数中正确使用this关键字
解决fetch回调中无法访问this的问题
你遇到的问题是因为普通function回调会创建独立的this上下文,和组件实例的this不是同一个引用,所以没法直接调用this.setState。这里有几种简单有效的修复方法:
方法1:使用箭头函数(最推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this,刚好就是你的组件实例。修改后的代码如下:
fetch(config.apiUrl + '/api/user', { headers: authHeader(), method: 'GET', }) .then(res => res.json()) // 替换为箭头函数 .then(data => { this.setState({ id: data.id }); // 现在可以正常访问组件的this了 });
方法2:提前保存this到变量
在fetch调用前,把组件的this赋值给一个变量(比如that或者self),然后在回调里用这个变量代替this:
const that = this; // 先把组件的this存起来 fetch(config.apiUrl + '/api/user', { headers: authHeader(), method: 'GET', }) .then(function(res) { return res.json(); }) .then(function(data) { that.setState({ id: data.id }); // 使用保存的that来调用setState });
方法3:用bind绑定this
通过bind()方法把组件的this绑定到回调函数上,强制让函数内部的this指向组件实例:
fetch(config.apiUrl + '/api/user', { headers: authHeader(), method: 'GET', }) .then(function(res) { return res.json(); }) .then(function(data) { this.setState({ id: data.id }); }.bind(this)); // 把组件的this绑定到这个回调函数上
这三种方法里,箭头函数是最简洁、最符合现代JavaScript写法的,推荐优先使用它。
内容的提问来源于stack exchange,提问作者Hareesh S
相关产品推荐
相关产品推荐

