[英]React “TypeError: imageCollection.map” is not a function only after state update
So I am building a little app to practice my skills and im grabbing images from the pixabay API.所以我正在构建一个小应用程序来练习我的技能并从 pixabay API 中抓取图像。
I want to be able to search images and automatically update when the user clicks the search button我希望能够搜索图像并在用户单击搜索按钮时自动更新
On load the code loads some of the images加载时代码会加载一些图像
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);
}
}, []);
Then I have a search bar that when you click on search it updates the state然后我有一个搜索栏,当您单击搜索时,它会更新 state
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);
}
This is how I am printing out the images这就是我打印图像的方式
{
imageCollection
? imageCollection.map(img => {
return <Image link={img}/>
})
: ""
}
I get an error after I hit search, it loads fine before.点击搜索后出现错误,之前加载正常。
TypeError: imageCollection.map is not a function error
类型错误:imageCollection.map 不是 function 错误
You have a mistake here你这里有一个错误
setImageCollection(...imageCollection, new_images);
it should be like this应该是这样的
setImageCollection([...imageCollection, ...new_images]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.