ReactJS实现复选框勾选时向数组添加对象、取消勾选时移除对象的功能求助
问题排查与修正方案
我帮你看看这段代码的问题哈,主要有两个关键逻辑错误导致复选框的选中/取消功能不正常,咱们一步步来修正:
错误点分析
findIndex的判断逻辑反转findIndex方法在找到匹配元素时会返回它的索引(>=0),没找到时返回-1。你原代码里的if (callScheduleIds.findIndex(...)),如果匹配的元素是数组第一个(索引0),会被JS判定为false,直接进入else分支,完全搞反了判断逻辑。移除元素时的索引获取错误
你用callScheduleIds.indexOf(id)来获取要删除的位置,但数组里存储的是对象而不是单独的id值,所以indexOf(id)永远返回-1,执行splice(-1,1)只会删除数组最后一个元素,根本不是你要移除的目标对象。
修正后的代码
const selectSingle = (id, item, index) => { const user = Cookies.get("user") && JSON.parse(Cookies.get("user")); // 拷贝原数组,避免直接修改状态 let callScheduleIds = [...allCallNotifications]; // 先获取目标对象的索引 const targetIndex = callScheduleIds.findIndex((obj) => obj.order_id === id); if (targetIndex === -1) { // 没找到,添加新对象 callScheduleIds.push({ order_id: id, phone_number: item.phone1, sender_id: user?.user?.id, // 可选链避免user不存在时报错 }); } else { // 找到对应索引,移除该元素 callScheduleIds.splice(targetIndex, 1); } setAllCallNotifications(callScheduleIds); };
额外优化点
- 用扩展运算符
[...allCallNotifications]拷贝数组,比Object.assign更直观易读; - 添加可选链
user?.user?.id,避免Cookies.get("user")不存在时出现Cannot read property 'user' of undefined的错误; - 把
findIndex的结果存到变量里,避免重复遍历数组,提升一点点性能。
这样修改后,当用户勾选复选框时,会把对应对象加入数组;取消勾选时,就能精准移除对应的对象啦~
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

