【发布时间】: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