【问题标题】:React useState update problematicReact useState 更新有问题
【发布时间】:2020-07-20 18:42:42
【问题描述】:

你好 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,但这是要走的路吗?

【问题讨论】:

  • 是的,这就是要走的路,将itemsCopy 传递给checkUnique,然后使用它来过滤数组并检查它是否有重复。
  • 好的,但有时我可以在没有参数itemsCopy 的情况下调用方法checkUnique。 items参数是否应该获得默认值?:const checkUnique = async (email, arr = items)
  • 这可能行得通,但您不应该依赖items 始终保持最新状态,您可能会得到奇怪的结果。我要做的是尽量让这个函数保持“纯”,并始终传递所有必需的参数,以便更容易调试,而不是依赖于checkUnique 范围之外的变量。

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


【解决方案1】:

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

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
}
};

【讨论】:

  • 这对任何事情都没有帮助。
  • 您的解决方案与我当前的示例有何不同?
猜你喜欢
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2021-03-01
相关资源
最近更新 更多