将一个元素添加到列表中,如果该元素不存在于列表中。如果该元素已经存在于列表中,则将其移除。

4
我希望将一个项目推送到列表中,如果之前没有包含它。如果已经存在,则删除该项目。我能够完成第一个部分,但不知道如何执行删除操作。
 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”部分会是什么呢?

2个回答

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

很好,乐意帮助 ;) - lissettdm

0

完成的应用程序:

enter image description here

过滤函数:

 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并使用修改后的tempList更新cities状态,否则,我们只需设置过滤出的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 链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接