由于是 React 和 js 的初学者,我很难正确构建数组, 我在网上找到一篇文章,说使用concat方法可以构造一个数组。我也遵循同样的技术, 但我的问题是它附加数据并比较是否已经存在相同的数据。 我想在附加到数组之前比较数据,这样就不会有重复的数据进入数组。
我当前的代码是:
const [input, setInput] = useState([]) // state
const handleOnChange = (userInput) => {
// Add the userInput the list onChange of userInput
// Save userInput to React Hooks
setInput((input) => input.concat(userInput))
console.log(input)
}
这里 userInput 是一个具有多个字符串值的对象,例如
{id: 1 , ifYes: "Do this", ifNo : "Do something else"}
如果数组中有 id:1 的项目,那么再次点击它,它不应该追加到数组中。
最佳答案
您可以使用数组find
来检查数组是否有具有相同id的对象,如果没有则可以添加值
const [input, setInput] = useState([]) // state
const handleOnChange = (userInput) => {
// Add the userInput the list onChange of userInput
// Save userInput to React Hooks
const hasUserInput = input.find(userVal => userVal.id === userInput.id);
if (!hasUserInput) {
setInput((input) => input.concat(userInput));
console.log(input)
}
}
关于javascript - 如何构造一个数组以首先比较然后添加输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71544521/