选中复选框时将对象推送到数组中,并在 ReactJS 中取消选中复选框时删除对象

Push object in array when checkbox is checked and remove object when checkbox is unchecked in ReactJS

我正在尝试实现一个功能,我想在用户选中对象时将其推送到数组中,并在用户取消选择时将其删除。我有一个菜单,用于收集用户选择。我已经实现了代码,但它没有解决我的问题,有人可以帮我解决这个问题吗?谢谢

  const selectSingle = (id, item, index) => {
    const user = Cookies.get("user") && JSON.parse(Cookies.get("user"));
    let callScheduleIds = Object.assign([], allCallNotifications);

    if (callScheduleIds.findIndex((item) => item.order_id === id)) {
      callScheduleIds.push({
        order_id: id,
        phone_number: item.phone1,
        sender_id: user.user.id,
      });
    } else {
      callScheduleIds.splice(callScheduleIds.indexOf(id), 1);
    }
    setAllCallNotifications(callScheduleIds);
  };

您可以使用 Lodash

 const selectSingle = (rowIndex, item) => {
    let callIds = Object.assign([], allCallNotifications)

    if (_.findIndex(callIds, { id: item.id }) === -1) {
      callIds.push(item)
    } else {
      callIds.splice(_.findIndex(callIds, { id: item.id }), 1)
    }

    setAllCallNotifications(callIds)
  }