简体   繁体   English

使用 onClick 从列表中删除单个项目

[英]Remove a single item from the list with onClick

I have the following object with multiple object arrays.我有以下带有多个对象数组的对象。 I would like to know how I can remove a single item from the list with onClick.我想知道如何使用 onClick 从列表中删除单个项目。

I know I can try it with the splice, but I have no idea how to do it within this object shape我知道我可以用拼接来尝试,但我不知道如何在这个对象形状内做到这一点

State状态

const [filters, setFilters] = useState(initialData || [])

I tried like this我试过这样

HandleClick手柄点击

const handleClick = () => {
    const newState = filters
    const index = newState[key].findIndex((a) => a.id === id)

    if (index === -1) return
    newState[key].splice(index, 1)

    setFilters(newState)
  }

Data Object数据对象

{
  "services": [
    {
      "id": "1b975589-7111-46a4-b433-d0e3c0d7c08c",
      "name": "Account"
    },
    {
      "id": "91d4637e-a17f-4b31-8675-c041fe06e2ad",
      "name": "Income"
    }
  ],
  "accountTypes": [
    {
      "id": "1f34205b-2e5a-430e-982c-5673cbdb3a68",
      "name": "Investment"
    }
  ],
  "channels": [
    {
      "id": "875f8350-073e-4a20-be20-38482a86892b",
      "name": "Chat"
    }
  ]
}

Render onClick点击渲染

<div onClick={handleClick}>
   <Icon fileName="smallClose" />
</div>

when you print the compinent make sure to add them the id of your array当您打印组件时,请确保将它们添加到您的数组的 id


<div id={idOfItem} onClick={handleClick}>
   <Icon fileName="smallClose" />
</div>
…….


function handleClick (e) {

e.preventDefault();
const {id} = e.target;

const list = yourItems.filter(item=> item.id!== id);

setItems(list);

}

Maybe it is because you are not declaring the "id" variable anywhere?也许是因为您没有在任何地方声明“id”变量? You can send the element id on the div event if it is on a map loop.如果它在地图循环中,您可以在 div 事件上发送元素 id。 I think that could fix your problem.我认为这可以解决您的问题。

<div onClick={() => handleClick(id)}>

And then import it as a parameter on your function:然后将其作为参数导入您的函数:

 const handleClick = (id) => {
    const newState = filters
    const index = newState[key].findIndex((a) => a.id === id)

    if (index === -1) return
    newState[key].splice(index, 1)

    setFilters(newState)
  }

Also, when you declare the newState value, make sure to use spread operators on the declaration, in your current behavior you are mutating your state and that is not recommended in react:此外,当您声明 newState 值时,请确保在声明中使用扩展运算符,在您当前的行为中,您正在改变您的状态,并且不建议在反应中这样做:

const newState = [...filters];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM