亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果列表中不存在某個項目,我想將其推送到列表中。如果該項目已在列表中,則刪除該項目

如果列表中不存在某個項目,我想將其推送到列表中。如果該項目已在列表中,則刪除該項目

冉冉說 2023-09-14 18:02:38
如果某個項目以前未包含在列表中,我想將其推送到列表中。如果存在,則刪除該項目。我能夠完成第一部分,但不知道如何刪除它。 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 });  };其他部分是什么?
查看完整描述

2 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

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

  };


查看完整回答
反對 回復 2023-09-14
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

過濾功能:


?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比較 的大小,如果相同則說明該城市名稱不存在于主列表中,因此我們將其推送到并使用 modded更新狀態,否則,我們只需設置過濾掉的。tempListcitiesnametempListcitiestempListtempList


完整示例:



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>

? );

}

代碼沙箱鏈接


查看完整回答
反對 回復 2023-09-14
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號