反应useState更新有问题

时间:2020-04-08 11:06:15

标签: reactjs use-effect react-state-management use-state

Hello 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作为参数,但这是可行的方法吗?

1 个答案:

答案 0 :(得分: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
}
};