使用“ useState”将图像文件添加到反应状态

时间:2020-04-30 23:43:04

标签: javascript reactjs amazon-web-services amazon-s3

import React, { useState } from "react";

export default function App() {
  const [photo, setPhoto] = useState([]);
  const pictures = listObjects();  // getting image flies from AWS.S3, and they are array of objects, and the key "Key" contains image files like "dog.gif"
  const getAllPictures = (pics) => {
    pics.then((data) => {
      return data.forEach((picture) => {
        // console.log(picture.Key); I've got a stirng img file
        setPhoto((photo) => [...photo, picture.Key]);
      });
    });
  };
  getAllPictures(pictures);

嗨。我试图使用挂钩将图像文件列表(例如“ dog.gif”)置于反应状态,并且我使用了包装函数。现在,我在本地服务器上看不到任何错误,但是几秒钟后,笔记本电脑风扇旋转,直到关闭浏览器后再也没有停止过,而且偶尔我还能在笔记本电脑上看到旋转的沙滩球。我猜想我将列表放入状态做错了,或者我从AWS.S3中获取了太多数据。有人可以指出我在做什么错吗?

2 个答案:

答案 0 :(得分:1)

您可能需要设置一次状态,否则它将陷入无限的重新渲染循环。
您可以使用useEffect钩子在组件安装上初始化一些数据。

以下是使用useEffect的示例:

print(df3)



   A  Base  Base_Chg  Base_5D_Chg  Year_Low  Year_High  Market_Cap  PE_Ratio  \
0  0     0         0            0         0          0           0         0   
1  1     0         0            0         0          0           0         0   
2  2     0         0            0         0          0           0         0   
3  3     0         0            0         0          0           0         0   

   SMA_50  SMA_100  SMA_200  RSI  ADX  ATR  STDEV  
0       0        0        0    0    0    0      0  
1       0        0        0    0    0    0      0  
2       0        0        0    0    0    0      0  
3       0        0        0    0    0    0      0  

当前实现有什么问题

import React, { useState, useEffect } from "react";

export default function App() {
  const [photo, setPhoto] = useState([]);

  const getAllPictures = (pics) => {
    pics.then((data) => {
      return data.forEach((picture) => {
        // console.log(picture.Key); I've got a stirng img file
        setPhoto((photo) => [...photo, picture.Key]);
      });
    });
  };

  useEffect(() => {
    const pictures = listObjects();
    getAllPictures(pictures);
  }, [])

答案 1 :(得分:1)

@Yuya,问题与使用react功能组件获取和设置数据有关。 useEffect挂钩非常适合通过设置状态而引起副作用(重新渲染)的api请求。 Simon写的是正确的,除了钩子还需要从顶部导入,就像这样

import React, { useState, useEffect } from "react";

此外,getAllPictures api调用看起来有点不正常。

pics.then((data) => {
   return data.forEach((picture) => {
   // The setState will trigger a re-render
     setPhoto((photo) => [...photo, picture.Key]);
   });
});

pics对象,而不是承诺。进行pic.then会产生类型错误。有关.then使用的更多详细信息,请查看此stackoverflow answer。我猜电话应该看起来像这样:

getAllPictures('http://url/to/the/endpoint').then((data) => {...})