我有一个要添加标签的项目,类似于此站点。我想先检查用户是否已经选择了标签。我有一个for循环,以查看添加的标签是否等于已经存在的标签。
如果我创建一个名为Jack的标签,它将正常工作。如果我创建另一个名为Jack的标签,现在我有两个Jacks(不好)。在第三次尝试时,它不会添加另一个Jack(很好)。
这是我的相关代码。我也添加了控制台。我的useState setTagAlreadyThere on在第三次尝试之前将被忽略,而在第二次尝试时应变为true。我在这里做错了什么?
const [tagsFound, setTagsFound] = useState([])
const [tagsAdded, setTagsAdded] = useState([])
const [tagAlreadyThere, setTagAlreadyThere] = useState(false)
const gatherTags = (tags) => {
setTagAlreadyThere(false)
console.log(tagAlreadyThere)
if (tagsAdded.length === 0) {
setTagsAdded([...tagsAdded, tags]);
} else {
console.log(tagsAdded)
for (let i = 0; i < tagsAdded.length; i++) {
console.log(tagsAdded[i])
if (tags === tagsAdded[i]) {
console.log(tagsAdded[i])
console.log(tags)
setTagAlreadyThere(true)
console.log(tagAlreadyThere)
}
}
console.log(tagAlreadyThere)
if (tagAlreadyThere === false) {
setTagsAdded([...tagsAdded, tags]);
console.log(tagsAdded)
} else {
return
}
}
setPostTag('')
}
安慰。
TagAdder.tsx:9 jack
postarticle.tsx:64 false
postarticle.tsx:69 ["jack"]
postarticle.tsx:72 jack
postarticle.tsx:75 jack
postarticle.tsx:76 jack
postarticle.tsx:78 false
postarticle.tsx:81 false
postarticle.tsx:84 ["jack"]
post.tsx:6 {}
postarticle.tsx:92 (2) ["jack", "jack"]
post.tsx:6 {}
postarticle.tsx:
92
没有冒犯,但您的代码包含许多不必要的内容。
那么为什么会这样呢。因为您tagAlreadyThere
尚未更新。您正在检查它的价值。
const gatherTags = (tags) => {
if (!tagsAdded.inlcudes(tags)) {
setTagsAdded([...tagsAdded, tags]);
setPostTag('')
}
}
不需要 const [tagAlreadyThere, setTagAlreadyThere] = useState(false)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句