取消选中(删除)复选框中的最后一项并同时选中(添加)其他项,保留未选中的值并添加其他选中的值

uncheck (removing) last item in checkbox and check(adding) other at the same time , keeps the unchecked value and adds other checked value

这里只分配了一个人

现在取消勾选上一个人(已添加),勾选其他other

onSubmit ,然后添加两者

这是我的代码:

 const [assignCustomerId, setAssignCustomerId] = useState([]);

  const handleOnChange = (id, event) => {
    //checking the already present customers by id
    const alreadyAssignedDeliveryMan = deliveryBoy?.assigned_customers.map(
      (d) => d.milkman_buyer_customer_id
    );

    // here, if already customer is assigned in database then pushing new checked
    // and keeping the database data also
    if (assignCustomerId.length === 0) {
      for (let i = 0; i < alreadyAssignedDeliveryMan.length; i++) {
        assignCustomerId.push(alreadyAssignedDeliveryMan[i]);
      }
    } else {
      console.log("null");
    }
    //if user checked, then push it into state array
    //if user unchecked , then removing the item from array
    const checked = event.target.checked;
    if (checked === true) {
      assignCustomerId.push(id);
      setAssignCustomerId(assignCustomerId);
    } else if (checked === false) {
      for (var i = assignCustomerId.length - 1; i >= -1; i--) {
        if (assignCustomerId[i] === id) {
          assignCustomerId.splice(i, 1);
          setAssignCustomerId(assignCustomerId);
        }
      }
    }
  };

我认为这可以帮助您删除部分

let index = assignCustomerId.findIndex(x=>x===id)
assignCustomerId.splice(index, 1);
setAssignCustomerId([...assignCustomerId]);

问题

您正在改变 assignCustomerId 状态并将相同的数组引用保存回状态。更新“已分配的送货人员”时,代码直接推送到 assignCustomerId 数组中。此外,当 checked 为真时,代码直接推入 assignCustomerId 数组,当 checked 为假时,.splice 执行 in-place 突变

if (assignCustomerId.length === 0) {
  for (let i = 0; i < alreadyAssignedDeliveryMan.length; i++) {
    assignCustomerId.push(alreadyAssignedDeliveryMan[i]); // <-- state mutation!
  }
} else {
  console.log("null");
}

const checked = event.target.checked;
if (checked === true) {
  assignCustomerId.push(id); // <-- state mutation!
  setAssignCustomerId(assignCustomerId);
} else if (checked === false) {
  for (var i = assignCustomerId.length - 1; i >= -1; i--) {
    if (assignCustomerId[i] === id) {
      assignCustomerId.splice(i, 1); // <-- state mutation!
      setAssignCustomerId(assignCustomerId);
    }
  }
}

解决方案

assignCustomerId 数组添加值时创建浅表副本并附加新元素值。当从 `assignCustomerId 数组中删除一个值时,然后过滤它并 return 一个新的数组引用。

if (!assignCustomerId.length) {
  setAssignCustomerId(state => state.concat(alreadyAssignedDeliveryMan));
} else {
  console.log("null");
}

const { checked } = event.target;

if (checked) {
  setAssignCustomerId(state => [...state, id]);
} else {
  setAssignCustomerId(state => state.filter((el) => el !== id));
}