Javascript 如果列表中没有项目,我想将其推送到列表中。如果该项目已在列表中,则删除该项目

Javascript 如果列表中没有项目,我想将其推送到列表中。如果该项目已在列表中,则删除该项目,javascript,reactjs,dom-events,Javascript,Reactjs,Dom Events,如果某个项目以前未包含在列表中,我想将其推送到列表中。如果有,则删除该项目。我可以做第一部分,但不知道如何删除它 handleCityCheckbox = (param1) => { var { cityList = [] } = this.state; //if cityList doesnt have param1 if (!cityList.includes(param1)) { cityList.push(param1); th

如果某个项目以前未包含在列表中,我想将其推送到列表中。如果有,则删除该项目。我可以做第一部分,但不知道如何删除它

 handleCityCheckbox = (param1) => {
    var { cityList = [] } = this.state;
      //if cityList doesnt have param1
    if (!cityList.includes(param1)) {
      cityList.push(param1);
      this.setState({ cityList });
    } else  {
      
    }
    this.setState({ cityList });
  };
其他部分是什么?

完成的应用程序:

过滤功能:

 const handleSubmit = (event) => {
    event.preventDefault();
    if (!name) {
      alert("Enter the city name");
      return;
    }
    let tempList = cities.filter(
      (city) => city.toLowerCase() !== name.toLowerCase()
    );

    if (tempList.length === cities.length) {
      tempList.push(name);
      setCities(tempList);
      return;
    } else {
      setCities(tempList);
    }
  };
在上述功能中,我们将首先使用
filter
功能进行筛选,即删除存在的城市名称,并将其分配给
templast
,然后将
templast
的大小与主
城市
列表进行比较,如果相同,则表明城市名称不在主列表中,因此我们将把
名称
推到
tempList
并使用修改的
tempList
更新
城市
状态,否则,我们只需设置筛选出的
tempList

完整示例:


import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [cities, setCities] = useState(["Pune", "Delhi"]);
  const [name, setName] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!name) {
      alert("Enter the city name");
      return;
    }
    let tempList = cities.filter(
      (city) => city.toLowerCase() !== name.toLowerCase()
    );

    if (tempList.length === cities.length) {
      tempList.push(name);
      setCities(tempList);
      return;
    } else {
      setCities(tempList);
    }
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input onChange={(event) => setName(event.target.value)} />
        <button type="submit">Submit</button>
      </form>
      {cities.map((city) => (
        <p>{city}</p>
      ))}
    </div>
  );
}


从“React”导入React,{useState};
导入“/styles.css”;
导出默认函数App(){
const[cities,setCities]=useState([“浦那”,“德里]);
const[name,setName]=useState(“”);
const handleSubmit=(事件)=>{
event.preventDefault();
如果(!name){
警报(“输入城市名称”);
返回;
}
让tempList=cities.filter(
(城市)=>city.toLowerCase()!==name.toLowerCase()
);
if(templast.length==cities.length){
圣殿骑士。推(名字);
塞西提斯(圣殿骑士);
返回;
}否则{
塞西提斯(圣殿骑士);
}
};
返回(
setName(event.target.value)}/>
提交
{城市地图((城市)=>(
{城市}

))} ); }

谢谢。工作很完美,很乐意帮忙;)
handleCityCheckbox = (param1) => {
    const { cityList = [] } = this.state;
    const itemIndex = cityList.indexOf(param1);
    if (itemIndex === -1)) {
      cityList.push(param1);
    } else  {
      cityList = cityList.filter((e, index) => index !== itemIndex)
    }
    this.setState({ cityList });
  };