0

你好 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 调用中删除的项目。而且我不想记住删除的项目,因为它很难理解和冗余。有谁知道如何解决这个问题?我考虑过传递itemsCopycheckUnique作为参数,但这是要走的路吗?

4

1 回答 1

0

就这样使用它;应该有帮助;

const handleRemoveItem = async (index) => {
const itemEmail = items[index].email;

setItems((prevState) => {
  return prevState.splice(index, 1);
});

const isUnique = await checkUnique(itemEmail);
if (!isUnique) {
  // do something
}
};
于 2020-04-08T11:28:21.193 回答