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

I want to push an item in a list if its not there . If the item already in the list then remove that item

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

 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 });
  };

else 部分是什么?

完成的应用程序:

过滤功能:

 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函数进行过滤,即删除存在的城市名称并赋值给tempList,然后比较大小tempList 与主 cities 列表,如果相同则表明主列表中不存在城市名称,因此我们会将 name 推送到 tempList 并更新cities 状态修改 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>
  );
}

Codesandbox Link

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 });
  };