【发布时间】:2019-05-08 12:18:45
【问题描述】:
我正在尝试使用 flicker getinfo 请求按标题或描述过滤图像,该请求会返回此信息。
我要做的是为当前图像数组中的每个图像发送一个 getinfo 请求,查看标题或描述是否与用户输入匹配,如果匹配则呈现这个新的过滤图像数组。
我无法解决我应该如何调用每个图像,只有在循环结束并且过滤数组完成后,然后在该数组上调用 setState。
filterImages = (filter) =>{
if(filter.length === 0)
return;
const currentImages = this.state.images;
console.log(currentImages[0]);
const newFilterdImages =[];
const baseUrl = 'https://api.flickr.com/';
for (const img of currentImages){
axios({
url: `services/rest/?method=flickr.photos.getinfo&api_key=22c1f9009ca3609bcbaf08545f067ad&photo_id=${img.id}&&format=json&safe_search=1&nojsoncallback=1`,
baseURL: baseUrl,
method: 'GET'
})
.then(res=> res.data)
.then(res=> {
if( res && res.photo) {
const imageInfo = res.photo;
//console.log(imageInfo.title._content,imageInfo.description._content);
if(imageInfo.title._content.includes(filter) || imageInfo.description._content.includes(filter)){
newFilterdImages.push(img);
}
}
}).then( res => console.log("first then " + newFilterdImages)) // output the newFilterdImages array on each call
}
this.setState({images:newFilterdImages}) // this will not work
}
我怎样才能等待这个循环结束,然后才用新的滤镜图像更改当前数组?
【问题讨论】:
-
您正在混合异步和同步代码。 Promise 是异步的,所以
newFilterdImages.push(img);将在this.setState({images:newFilterdImages})之后执行