JavaScript 在 Array.prototype.find() 中“元素未定义”

问题描述 投票:0回答:1

我正在 ReactJS 中构建一个使用标签来组织照片的应用程序。我的数据结构由三部分组成:(1)照片,(2)标签和(3)“imageTags”,它们是照片和标签之间的关系。对于 ID 为 9、12 和 35 且标签分别为 4、5 和 6 的照片,imageTag 对象将如下所示:

const imageTags = {
  {id: 1, imageId: 9, tagId: 4},
  {id: 2, imageId: 12, tagId: 5},
  {id: 3, imageId: 35, tagId: 6}
} 

“标签”组件仅传递 imageTag id,从中它应该能够确定分配给它的图像,以及该图像上应该存在的标签,如下所示:

// props: imagetagId={7}
const imageId = imageTags.find(element => element.id === props.imageTagId)

这对于初始渲染效果很好。但是,当用户尝试从照片中删除标签时,*应用程序的状态会发生变化,我突然收到错误:

Uncaught TypeError: element is undefined

我不明白的是,“元素”怎么可能是未定义的?我的理解是,它正在遍历 imageTags 对象并检查每个“元素”,因此我以这种方式命名变量。我知道这不是“imageTags.find(...) 未定义”的问题,也不是 find 方法不返回任何结果。对我来说,错误看起来好像元素本身未定义......但这怎么可能?

这是当用户尝试删除标签时更改 imageTags 的函数:

// remove a specific imageTag from imageTags
const handleRemoveTag = (imageTagId) => {
  for (const [key, value] of Object.entries(imageTags)) {
    if (value.id == imageTagId) {
      delete imageTags[key];
    };
  };
};

*我发现的另一个重要细节:删除列表中的最后一个标签时不会发生此错误。从最后一个标签到第一个标签,可以安全地一次删除一个标签,但从中间或开头删除标签会导致此错误。我不确定为什么会这样,但它似乎与故障排除相关。

javascript reactjs arrays json dictionary
1个回答
0
投票

首先,为什么

imageTags
不能成为
Array

const imageTags = [               // <—-
  {id: 1, imageId: 9, tagId: 4},  //    |
  {id: 2, imageId: 12, tagId: 5}, //    |—- Array of Objects.
  {id: 3, imageId: 35, tagId: 6}  //    |
]                                 // <—-

其次,如果你打算改变这个

Array
,为什么要声明它
const

const imageTags
// instead
let imageTags [1]

最后,要从

imageTag
中删除特定的
imageTags
,请使用此过程。

const handleRemoveTag = (imageTagId) => {
  let index = imageTags.findIndex(element => element.id === imageTagId)
  imageTags.splice(index, 1)
}

[1] 对于

Array.prototype.splice()
的某些实现,这并不重要。

© www.soinside.com 2019 - 2024. All rights reserved.