代码之家  ›  专栏  ›  技术社区  ›  Thanveer Shah

react todo list:如何检查数组中是否已存在项*已解决*

  •  0
  • Thanveer Shah  · 技术社区  · 7 年前

    我尝试了一种简单的方法,但这种方法似乎不起作用。

    我想在单击按钮时检查该项是否存在。使用if语句

    //Adding Items on Click
    
     addItem = () =>
     {
    
        let newValue = this.state.inputValue;
        let newArray = this.state.inputArray;
    
        if (newValue === newArray) {
          console.log("Exist");   // this part doesnt work
        } else {
          newArray.push(newValue);  //Pushing the typed value into an array
        }
        this.setState({
          inputArray: newArray //Storing the new array into the real array
        });
        console.log(this.state.inputArray);
      };
    

    解决了的

    使用if(newarray.includes(newvalue)而不是if(newvalue==newarray)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jayavel    7 年前

    按如下方式更改您的功能:

     addItem = () =>
        {
    
        let newValue = this.state.inputValue;
        let newArray = this.state.inputArray;
    
        if (newArray.includes(newValue)) {
          console.log("Exist");   
          return;
        } 
        this.setState(previousState => ({
          inputArray: [...previousState.inputArray, newValue]
        }, () =>  console.log(this.state.inputArray)));
    
      };
    

    不要直接将新值推送到状态,而是使用它,如下所示:

    this.setState(previousState => ({
      inputArray: [...previousState.inputArray, newValue]
    }, () =>  console.log(this.state.inputArray)));
    

    let inputArray= [...this.state.inputArray];
    inputArray.push("new value");   
    this.setState({inputArray})