你好 Stackoverflow 社区,
我对 useState 有一个难题。我想从数组中删除一个项目,然后我想做一些检查和一个 xhr 调用。让我给你举个例子:
const [items, setItems] = useState([{ id: 'xxx', email: 'xxx@xxx.com' }, { id: 'yyy', email: 'xxx@xxx.com' }]);
const handleRemoveItem = async (index) => {
const itemEmail = items[index].email;
const itemsCopy = [...items];
itemsCopy.splice(index, 1); <-- Remove one item, one should be left
setItems(itemsCopy);
const isUnique = await checkUnique(email);
if(!isUnique) {
// do something
}
}
const checkUnique = async (email) => {
const hasDuplicates = items.filter(item => item.email === email).length > 1; <-- items has already 2 items, but before one was removed
if(hasDuplicates) {
return false;
}
// Some XHR calls to check the email already exists
}
问题是,项目中checkUnique
仍然包含两个项目。我不能使用 useEffect,因为我需要在 xhr 调用中删除的项目。而且我不想记住删除的项目,因为它很难理解和冗余。有谁知道如何解决这个问题?我考虑过传递itemsCopy
给checkUnique
作为参数,但这是要走的路吗?