React Hooks useState数组渲染两次

时间:2020-06-15 18:39:20

标签: javascript arrays reactjs react-hooks

我需要通过使用函数将图像上传到useState,然后我要呈现此图像,问题是我不知道如何呈现返回的数组,这里是代码 代码:

  const [logoImg, logoUpdater] = useState();
  const [title, updateTitle] = useState();
  const [carouselImages, carouselImagesUpdater] = useState([]);
  useEffect(
    (e) => {
      if (carouselImages.length > 0) {
      }
    },
    [carouselImages]
  );

  const carouselUploader = (file) => {
    var addedFile = file.target.files[0];
    carouselImagesUpdater((carouselImages) => [...carouselImages, addedFile]);
  };
  const titleFunction = () => {
    Preview(title);
  };
  return (
    <div>

      <div>
        <p>Upload Carousel images</p>
        <input
          type="file"
          accept="image/*"
          multiple
          onChange={(e) => carouselUploader(e)}
        ></input>
        {carouselImages.map((img) => (
          <img src={img} key="s"></img>
        ))}

1 个答案:

答案 0 :(得分:1)

多次重新渲染并不能显示所选文件的损坏图像。这是一个如何设置文件的示例:

const App = () => {
  const [
    carouselImages,
    carouselImagesUpdater,
  ] = React.useState([]);
  const carouselUploader = (e) => {
    const reader = new FileReader();
    reader.addEventListener('load', (event) => {
      carouselImagesUpdater((carouselImages) => [
        ...carouselImages,
        event.target.result,
      ]);
    });
    reader.readAsDataURL(e.target.files[0]);
  };
  return (
    <div>
      <p>Upload Carousel images</p>
      <input
        type="file"
        accept="image/*"
        multiple
        onChange={(e) => carouselUploader(e)}
      ></input>
      {carouselImages.map((img, index) => (
        <img key={index} src={img}></img>
      ))}
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

Here是一些有关如何读取文件的文档。