从状态中删除点击的值

I am using react-admin framework. I am trying to dynamically remove value from state (id), if the value is in the state present more than once. My use case is to create checkboxes, so if one checkbox is clicked twice it deselects.

到目前为止,我有以下代码:

private addIdsToObj = (id: any) =>
{
   const Ids = [...this.state.selectedIds, id];
   this.setState({ selectedIds: Ids });
   if (Object.values(this.state.selectedIds).includes(id) === true)
   {
      const index = this.state.selectedIds.indexOf(id);
      if (index > -1)
      {
           const newState = this.state.selectedIds.splice(index, 1);
           this.setState({ selectedIds: newState });
      }
   }
}

But it behaves weirdly. Right now it only removes every value from the state apart from the clicked one, that should be removed in the first place. I am really stuck with this.

有什么想法我做错了吗?

先感谢您。

评论
  • Wolf
    Wolf 回复
    private addIdsToObj = (id: any) =>
    {
       const Ids = [...this.state.selectedIds, id];
       this.setState({ selectedIds: Ids }, () => {
           ....your code
       });
    }