如何根据字符串匹配 id 从数组中删除字符串

How to remove a string from an array based on string matching id

我目前正在呈现一个复选框,如果选中,数据(字符串中的 id)将保存在状态中。但是,我正在尝试将功能放在一起,如果未选中该复选框,则需要从状态(它是一个字符串数组)中删除数据。

我想出了这个解决方案,但我认为我没有正确使用 .splice 或者这是否是我使用的最佳选择,因为它不起作用。

<Checkbox
        onChange={(e) => {
          e.target.checked
            ? setSelectedStyles([...selectedStyles, s.id])
            : e.target.checked === false &&
              selectedStyles.map((id) => id === s.id)
            ? selectedStyles.splice(s.id)
            : console.log(`didn't work`)
        }}
      ></Checkbox>

澄清一下,selectedStyles 是一个存储在状态中的字符串数组。 s.id 是我要检查的 ID(字符串)。

有人对如何解决这个问题有任何想法吗?

提前致谢

试试这个:

onChange={(e) => {
  e.target.checked
  ? setSelectedStyles([...selectedStyles, s.id])
  : setSelectedStyles(selectedStyles.filter(x => x !== s.id))
}}

filter方法允许克隆数组,同时删除所需的项目。

你永远不应该像你试图用 splice 那样改变 React 状态。