【问题标题】:Getting an error that images is null while trying to show a preview of the uploaded images in react js尝试在 React js 中显示上传图像的预览时出现图像为空的错误
【发布时间】:2021-02-22 06:42:18
【问题描述】:

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

这是代码:

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>

【问题讨论】:

  • setImages 定义在哪里?
  • 嘿,我把它定义为const [images, setImages] = useState(null);
  • 代码中应该也有。我猜是有问题。
  • 哦..好的,感谢您告诉我。我会更新问题。

标签: javascript reactjs react-native foreach rxjs


【解决方案1】:

通过您的setImages({ images: imageArray }) 调用,您将获得images const 的值:

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

所以您必须以images.images 访问它,或者将其设置为setImages(imageArray),这样您就可以按预期访问。

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

【讨论】:

  • 好的。谢谢,我会检查并回复您。 :)
【解决方案2】:
{imageArray.length>0 ? 
<div>
  {imageArray.map((element)=>{
  return(
    <img src={element} alt="" />
    )
  })}
</div>
:null}

希望能解决

【讨论】:

  • 您好,感谢您的回复。但仍然没有显示图像。
  • 你能在我们试图映射的位置分享一个 imageArray 的 sc 吗?
  • 实际上,我正在尝试使用此函数uploadMultipleFiles 选择文件后显示图像,然后在此过程中附加数组imageArray,然后显示该数组中的图像。所以我猜 imageArray 是来源。希望这就是你所要求的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多