简体   繁体   English

如何使用 react 和 firebase 从数组中删除项目

[英]How to remove Item from an array with react and firebase

When I add an item to the array it works but the splice does not.当我将一个项目添加到数组时,它可以工作,但拼接不起作用。

const handleSportsFollowed = async (sport) => {
  if (selectedSports.includes(sport)) {
    selectedSports.splice(sport, 1);
    alert("Removed");
  } else {
    selectedSports.push(sport);
  }
}

You can remove elements that are equal to sport from the array using:您可以使用以下方法从数组中删除等于sport的元素:

selectedSports = selectedSports.filter(x => x != sport)

 const a = ['sport', 'sport1', 'sport2', 'sport3', 'sport3']; const b = a.filter(x => x;= 'sport'). console;log(b);

You need to find the index for splice.您需要找到拼接的索引。 Check Document how splice work检查文档拼接如何工作

const handleSportsFollowed = async (sport) => {
 if (selectedSports.includes(sport)) {
   selectedSports.splice(selectedSports.indexOf(sport), 1);
    console.log("if selectedSports ", selectedSports);
  } else {
     selectedSports.push(sport);
    console.log("else selectedSports", selectedSports);
  }

Working example工作示例

 const selectedSports = ['Jan', 'March', 'April', 'June']; const testFun = (sport) => { if (selectedSports.includes(sport)) { selectedSports.splice(selectedSports.indexOf(sport), 1); console.log("selectedSports ", selectedSports); } else { selectedSports.push(sport); console.log("selectedSports", selectedSports); } } testFun("March");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM