【问题标题】:Cannot map through array of files/images React无法通过文件/图像数组映射React
【发布时间】:2022-01-02 15:03:56
【问题描述】:

我正在 React 中创建一个图像上传组件。每次文件输入字段更改时,我都会更新images 状态。在输入字段下方,我试图遍历图像并将它们的名称记录在控制台中。但是,一旦我选择了图像,我就会收到错误 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;

【问题讨论】:

    标签: arrays reactjs file input


    【解决方案1】:

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

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

    Read here about array-like

    【讨论】:

      【解决方案2】:

      之前

      setImages(e.target.files)
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        • 2018-01-09
        • 2018-04-09
        相关资源
        最近更新 更多