无法通过 files/images React 数组进行映射

Cannot map through array of files/images React

我正在 React 中创建图像上传组件。每次文件输入字段更改时,我都会更新 images 状态。在输入字段下方,我试图遍历图像并将它们的名称记录在控制台中。但是,一旦我 select 图片,我就会收到错误 TypeError: images.map is not a function. 这是我的代码:

import React, { useState } from 'react';

const ImagesInput = (props) => {
    const [images, setImages] = useState([]);

    const imageInputChange = (e) => {
        setImages(e.target.files)
    }

    return (
        <div>
            <input {...props} type="file" onChange={imageInputChange} multiple />
            {images.map((image) => {
                console.log(image)
            })}
        </div>
    )
}

export default ImagesInput;

之前

setImages(e.target.files)

尝试添加这样的条件,确保e.target.files是你想要的图像

if(e.target.files){
  setImages(e.target.files)
}

e.target.files 的值是一个类似数组的数组,而不是实际的数组。在传递给 setImages 之前将其转换为数组,如

setImages([...e.target.files])

Read here about array-like