我有一个简单的输入表单,我在其中放置了一个字符串列表,然后对于字符串的每个元素(string[i](,我运行一个ajax Get请求到我的api。 所以这是 Ajax 请求:
async function getUsers(props){
try{
const response = await Axios.get(`url=`+props)
console.log(response)
return response;
}catch{
console.log("response failed")
}
}
我在这里运行它:
... some code here ...
for(var i =0; i < string.length; i++){ // map the entery (string)
getUsers(string[i]).then(res => {
this.setState({
string2:res // this one is just for testing
});
console.log(res.data.id);
mystring22.push({res});
console.log("me inside the promise : " + this.state.string2.data.id);
})
setTimeout(() => {
console.log("iam not empty " + this.state.string2.data.id);
console.log(mystring22);
/* -----------------
I WANT TO DO SOME WORK HERE
-----------------*/
}, 3000);
this.setState({
string3 : mystring22
})
... some code here ...
所以一切正常,我的问题是以下几点: 代码花费太多时间(每个请求 3 秒(,有没有办法更改代码以便它可以在每个请求后执行"SOMETHING",我试图删除 setTimeout 或减少它,但在那之后数组不起作用是未定义的。 希望你能帮助我. 谢谢
setState
是一个异步函数,所以当你调用:
setState({ string2: res });
this.state.string2; // OUTDATED
为了访问更新的值,您必须使用回调:
setState({ string2: res },
() => { console.log(this.state.string2) }); // UP TO DATE
正如你在这个代码沙盒示例中所看到的,回调在第 27 行,没有回调在第 33 行。