由于是 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)