【问题标题】:React "TypeError: imageCollection.map" is not a function only after state update只有在状态更新后才反应“TypeError:imageCollection.map”不是一个函数
【发布时间】: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


【解决方案1】:

你错了

setImageCollection(...imageCollection, new_images);

应该是这样的

setImageCollection([...imageCollection, ...new_images]);

【讨论】:

  • 您好,感谢您的帮助。错误消失了,但状态没有更新,我检查了状态但它没有更新,我已经控制台记录了数组,那里肯定有图像..
猜你喜欢
  • 2020-12-02
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2021-05-01
相关资源
最近更新 更多