【发布时间】:2020-05-13 09:05:37
【问题描述】:
所以我正在构建一个小应用程序来练习我的技能并从 pixabay API 抓取图像。
我希望能够搜索图像并在用户单击搜索按钮时自动更新
在加载时,代码会加载一些图像
const [imageCollection, setImageCollection] = useState();
const searchTerm = useRef();
useEffect(() => {
if (!imageCollection) {
let images = [];
Axios.get('https://pixabay.com/api/?key=x=yellow+flowers&image_type=photo&per_page=10')
.then(res => {
res.data.hits.map(img => {
images.push(img.largeImageURL);
})
});
setImageCollection(images);
}
}, []);
然后我有一个搜索栏,当你点击搜索时它会更新状态
const handleSearch = () => {
let string = encodeURI(searchTerm.current.value).replace('%20', '+');
let new_images = [];
Axios.get('https://pixabay.com/api/?key=x=' + string + '&image_type=photo&per_page=10')
.then(res => {
res.data.hits.map(img => {
new_images.push(img.largeImageURL);
})
});
setImageCollection(...imageCollection, new_images);
}
这就是我打印图像的方式
{
imageCollection
? imageCollection.map(img => {
return <Image link={img}/>
})
: ""
}
点击搜索后出现错误,之前加载正常。
TypeError: imageCollection.map 不是函数错误
【问题讨论】:
-
imageCollection 是一个数组吗?
-
是的,我确实遇到了@aleksey 指出的错误
标签: javascript reactjs axios