作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试一种简单的方法,但这种方法似乎不起作用。
我想检查单击按钮时该项目是否存在。使用 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/
我是一名优秀的程序员,十分优秀!