React Native应用中axios回调内setState报错无法设置Ajax响应的问题
解决React Native中axios回调里setState报错的问题
这个问题我太熟悉了!你遇到的报错根源是回调函数里的this指向不对——普通function作为then的回调时,this已经不再指向你的React组件实例了,自然找不到setState方法。给你几个靠谱的解决办法:
方法1:使用箭头函数(最推荐)
箭头函数会自动继承外层作用域的this指向,也就是你的组件实例,这样就能正常调用setState了。另外要注意:setState是异步操作,如果你想查看更新后的状态,要放在它的第二个回调参数里,不然直接在setState后打印可能拿到的还是旧状态。
constructor(){ super(); this.state = { data: '' } } axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then((response) => { // 换成箭头函数 console.log(response); this.setState({data: response }, () => { // 在setState的回调里查看最新状态 console.log(this.state.data); }); }) .catch((error) => { // catch也可以换成箭头函数 console.log(error); });
方法2:提前保存组件的this
在axios请求前,把组件的this存到一个变量(比如that)里,之后在回调里用这个变量代替this:
constructor(){ super(); this.state = { data: '' } } const that = this; // 提前保存组件实例的引用 axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); that.setState({data: response }, () => { console.log(that.state.data); }); }) .catch(function (error) { console.log(error); });
方法3:用bind绑定this
通过bind(this)把组件的this绑定到回调函数上,强制改变它的指向:
constructor(){ super(); this.state = { data: '' } } axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); this.setState({data: response }, () => { console.log(this.state.data); }); }.bind(this)) // 绑定组件的this到当前函数 .catch(function (error) { console.log(error); }.bind(this));
以上三种方法都能解决你的问题,其中箭头函数的写法最简洁直观,也是现在React项目里最常用的方式。
内容的提问来源于stack exchange,提问作者Manikanta
相关产品推荐
相关产品推荐

