javascript - 尝试在 React js 中显示上传图像的预览时出现图像为空的错误
问题描述
我有这个功能可以上传多张图片并且它可以工作,现在我需要显示用户选择的所有图片的预览。我尝试使用map
andforEach
尝试循环显示图像,但它不起作用。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>
解决方案
通过您的setImages({ images: imageArray })
通话,您将获得images
const 的价值:
images = {images: [...]} // [...] is the imageArray
因此,您必须将其访问为images.images
,或者将其设置为setImages(imageArray)
可以按您期望的方式访问。
此外,访问状态变量并使用map
而forEach
不是imageArray
. 所以而不是imageArray.forEach(...)
使用images.map(...)
. Map 返回一个数组,其中包含从函数调用返回的值。而forEach
返回未定义。
推荐阅读
- matlab - 有没有办法在优化问题中从 matlab 中的 ND 变量中消除空列或行以解决参数维度问题?
- android - 检查可拖动的 ImageView 是否覆盖了任何可见的 RecyclerView 元素
- python - 是否有一个 Numpy/Scipy 函数用于在以指定的基础编写的给定区间内查找多项式的根?
- javascript - 无法从 Javascript 访问 JSON 数据
- python-requests - 使用 python 请求在网站上登录帐户
- android-studio - 如何在“其他”条件下取消 toast 消息,即使它仍然适用
- excel - excel中加班表特定日期的逻辑
- apache-kafka - 最大轮询记录在 nifi 中的 ConsumeKafka 处理器中没有给出正确的结果
- reactjs - 是否可以仅使用 Jwt 令牌带来该用户的订单?
- hash - 仅从时间戳解密哈希或创建新哈希