上传多张图片并保存到 React JS 中的数组

Upload multiple images and save to array in React JS

需要帮助获取使用以下代码上传的完整图片列表,然后将其保存到数组中:

const [pictures, setPictures] = useState([{
        data: [],
        url: ""
    }])

    const handleImageUpload = (e) => {

        [...e.target.files].forEach(file => {
            console.log("file >>> ", file)

                 setPictures([
                    ...pictures,
                    {
                        data: file,
                        url: URL.createObjectURL(file)
                    }
                ])

                console.log("pictures >> ", pictures)
            })
    }

每当我显示图片预览时,它只显示最后上传的图片所以我猜 input:file 是 运行 async

<div className="post__pictures">
    <input type="file" multiple 
        onChange={handleImageUpload}
        accept="image/*"
    />

        {pictures?.map(pic => (
            <img src={pic.url} />
        ))}
</div>

控制台日志中的结果如下

    file >>>  
        File {name: "software-development-coding-process-concept-260nw-1483883831.png", lastModified: 1609189641927, lastModifiedDate: Tue Dec 29 2020 01:07:21 GMT+0400 (Gulf Standard Time), webkitRelativePath: "", size: 14722, …}
        Post.js:51 
    
    pictures >>  
        [{…}]
        0: {data: Array(0), url: ""}
        length: 1
        __proto__: Array(0)
        Post.js:41 

file >>>  
        File {name: "software-language-programmer-avatar-vector-17866088.jpg", lastModified: 1609301370464, lastModifiedDate: Wed Dec 30 2020 08:09:30 GMT+0400 (Gulf Standard Time), webkitRelativePath: "", size: 131625, …}
        Post.js:51 
    
    pictures >>  
        [{…}]
        0: {data: Array(0), url: ""}
        length: 1
        __proto__: Array(0)
        Post.js:41 

file >>>  
        File {name: "stock-market-chart-600w-252511228.webp", lastModified: 1609532996651, lastModifiedDate: Sat Jan 02 2021 00:29:56 GMT+0400 (Gulf Standard Time), webkitRelativePath: "", size: 62182, …}
        Post.js:51 
    
    pictures >>  
        [{…}]
        0: {data: Array(0), url: ""}
        length: 1
        __proto__: Array(0)

它的发生是因为你 setState 在循环内部。像这样更新你的 handleImageUpload,它对我来说很好用。

如果您 setState 在循环内部,DOM 将在每个 setState 中重新呈现。这就是它显示最后一张图片的原因。

const handleImageUpload = e => {
  const tempArr = [];

  [...e.target.files].forEach(file => {
    console.log("file >>> ", file);

    tempArr.push({
      data: file,
      url: URL.createObjectURL(file)
    });

    console.log("pictures >> ", pictures);
  });

  setPictures(tempArr);
};