javascript - 在React组件中,如何使用fetch( )的返回值?
本文介绍了javascript - 在React组件中,如何使用fetch( )的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
React通过fecth异步加载数据,但是fecth之后,如何才能让我使用返回的值呢?
getInitialState:function(){
return{
result:''
}
},
proceedSubmit:function(userID,userPWD){
var res = 'Not Set';
fetch('http://127.0.0.1:80/csu/Search.php',{
method:'POST',
mode:'cors',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body:'userID='+userID+'&userPWD='+userPWD
}).then(function(response){
return response.text().then(function(text){
res = text;
console.log(res);
});
}).then(function(){
console.log(res);
});
console.log(res);
},
像这样跨域fecth之后,得到了返回值text,第一二个输出确实是返回的值,但是第三个却是初始的Not Set。我该怎么样才能使用fetch回来的值呢?让它改变我的state。
解决方案
proceedSubmit: function(userID, userPWD) {
var res = 'Not Set';
var _this = this; // <-------
fetch(....).then(function(response) {
_this.someData = text; // <-------
})
}
这篇关于javascript - 在React组件中,如何使用fetch( )的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文