REACT Todo-List:如何检查数组中是否已经存在一项

时间:2019-01-11 05:42:31

标签: javascript reactjs

我正在尝试一种简单的方法,但是这种方法似乎行不通。

我想检查单击按钮时项目是否存在。使用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);
  };

1 个答案:

答案 0 :(得分:1)

按如下所示更改您的功能:

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