我有一個項目要添加標簽,類似于這個站點。我想首先檢查用戶是否已經選擇了標簽。我有一個 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 jackpostarticle.tsx:64 falsepostarticle.tsx:69 ["jack"]postarticle.tsx:72 jackpostarticle.tsx:75 jackpostarticle.tsx:76 jackpostarticle.tsx:78 falsepostarticle.tsx:81 falsepostarticle.tsx:84 ["jack"]post.tsx:6 {}postarticle.tsx:92 (2) ["jack", "jack"]post.tsx:6 {}postarticle.tsx:92
For 循環僅適用于帶有 React 鉤子的第二個循環
慕桂英546537
2021-09-30 17:05:14