【问题标题】:Push object in array when checkbox is checked and remove object when checkbox is unchecked in ReactJS选中复选框时将对象推送到数组中,并在 ReactJS 中未选中复选框时删除对象
【发布时间】:2021-12-14 22:10:15
【问题描述】:

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

  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);
  };

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6 lodash


    【解决方案1】:

    你可以使用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)
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-19
      • 2021-07-25
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多