根据数组是否包含事件来添加或从数组中删除



我正在尝试用一个按钮将值添加到数组中,或者如果数组中已经存在该值,则删除该值。
该阵列称为toppings

const ToppingPlusMinus = (e) => {
if (toppings.includes(e.target.value, 1)) {
removeTopping(e)
}
else {
changeToppings(e);
}
}

的两个功能

const removeTopping = (e) => {
toppings.splice(e.target.value)
}
const changeToppings = (e) => {
setToppings([...toppings, e.target.value]);
};

按钮是披萨上的浇头,它们是这种格式的

<button
type="button"
value="Sausage, "
className="button btn first"
onClick={(event) => {
ToppingPlusMinus(event);
}}
>
Sausage
</button>

这可以很好地将值添加到数组中,但是在删除时会出现意外的结果。

  1. 只有在用户双击按钮后,项目才会被删除
  2. 移除还移除阵列中的顶部之前的顶部
  3. 当项目在数组中时,按钮不会保持活动状态(我还没有尝试过,但如果有人知道如何做到这一点,我将不胜感激(


我在这里用我的代码设置了一个代码沙箱我感谢你的帮助。

我已经在这个代码沙箱上做了一个工作示例,所以请检查一下!

你的代码不起作用的主要原因是toppings.splice(e.target.value)的使用,因为在这里你试图直接修改state,而没有遵循setting的正确流程。所以你需要正确地过滤掉它。

在我的例子中,我对值使用了不同的方法,但删除它们的逻辑也可以与您的方法保持不变。

首先,.includes不需要第二个参数。toppings.includes(e.target.value)应该是足够的。

其次,您应该定义这样的删除函数:

const removeTopping = (e) => {
setToppings((toppings) => {
return toppings.filter(topping => topping !== e.target.value)
})
}

这将导致使用不包含所选值的新数组设置toppings数组。您也可以将value直接传递给removeToppingchangeToppings函数。

因此,基本上您有一个项数组,如果存在,您希望删除项。

这是香草js解决方案:

let toppings = []; // this will hold the topping 
const ToppingPlusMinus = (e) => {    // this will trigger on click
if (toppings.indexOf(e.target.value) > -1) { // if the value of the button exist:
removeA(toppings, e.target.value);     // remove it
}
else {
toppings.push(e.target.value); // add it to the array
};
document.querySelector('#toppings').textContent = toppings.toString(); // this for demo
};
function removeA(arr) {
// https://stackoverflow.com/a/3955096/6525081
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
#toppings {font-size: larger;}
<button type="button" value="Sausage" className="button btn first" onClick="ToppingPlusMinus(event)">Sausage</button>
<button type="button" value="onion" className="button btn first" onClick="ToppingPlusMinus(event)">Onion</button>
<button type="button" value="olive" className="button btn first" onClick="ToppingPlusMinus(event)">Olive</button>
<div id="toppings"></div>

最新更新