首页 > 解决方案 > 尝试在 React js 中显示上传图像的预览时出现图像为空的错误

问题描述

我有这个功能可以上传多张图片并且它可以工作,现在我需要显示用户选择的所有图片的预览。我尝试使用mapandforEach尝试循环显示图像,但它不起作用。console.log(images)正在显示上传图像的 url,但images.map()images.ForEach正在引发 null 错误。谁能告诉我这有什么问题?我是新手,所以需要一些帮助。

这是代码:

const fileObj = [];
const imageArray = [];
const [images, setImages] = useState(null); 

const uploadMultipleFiles = (e) => {
    if (e.target.name === 'images') {
        fileObj.push(e.target.files)
        for (let i = 0; i < fileObj[0].length; i++) {
            imageArray.push(URL.createObjectURL(fileObj[0][i]))
            // console.log(imageArray)
        }
        setImages({ images: imageArray })
    }
}

{console.log(images)}
<div className="form-group multi-preview">
  { {(imageArray || []).map(url => (
         <img src={url} alt="" />
      ))} 
  }
</div>
                    
 <label htmlFor="images">
      <input
         accept="image/*"
         className={classes.input}
         id="images"
         onChange={uploadMultipleFiles}
         name="images"
         type="file"
         multiple
         ref={register({required:true})}
     />
     Images
     <IconButton color="primary" component="span">
         <PhotoCamera style={{fontSize:"xx-large"}} />
     </IconButton>
  </label>

标签: javascriptreactjsreact-nativeforeachrxjs

解决方案


通过您的setImages({ images: imageArray })通话,您将获得imagesconst 的价值:

images = {images: [...]} // [...] is the imageArray

因此,您必须将其访问为images.images,或者将其设置为setImages(imageArray)可以按您期望的方式访问。

此外,访问状态变量并使用mapforEach不是imageArray. 所以而不是imageArray.forEach(...)使用images.map(...). Map 返回一个数组,其中包含从函数调用返回的值。而forEach返回未定义。


推荐阅读