gpt4 book ai didi

javascript - REACT 待办事项列表 : How to check if an item already exist in the array

转载 作者:行者123 更新时间:2023-12-03 00:24:43 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于javascript - REACT 待办事项列表 : How to check if an item already exist in the array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com