如何解决使用期间的状态变化重点清理
我希望将对对象数组的更改发布到数据库中(可以非常快速地添加或删除这些对象),并且我不想在更改数组时就访问数据库(以避免在此类更改中进行过多的请求)短时间)。为此,我想在用户changes screens in React Native之后“保存”这些更改。我唯一的问题是在useEffects的clean up期间访问我的状态时发生的,在删除处理程序中我的状态按预期发生了变化,但是当触发清理后,状态几乎恢复为初始状态(使用useEffect设置) )。
export const ProfileView = () => {
const [userTags,setUserTags] = useState < EnumTags > profileData.tags;
// TODO: Avoid data from being saved and fetched everytime a tag is removed
useFocusEffect(
// Fetch Tag Data
React.useCallback(() => {
// *** Grab data from a JS object ***
console.log("----------------");
console.log("Tag data fetched");
console.log("----------------");
const tagData = [...profileData.tags];
setUserTags(tagData);
// *** EXPECTED LOG: 5 ***
// *** OUTPUT IS: 5 ***
console.log("- Before: ",userTags.length);
return () => {
// Save changes
// *** DURING CLEAN UP,SAVE DATA IN THE JS OBJECT
console.log("----------------");
console.log("Save changes");
console.log("----------------");
// *** EXPECTED OUTPUT IF A ELEMENT IS REMOVED: NOT 5 ***
// *** OUTPUT: 5,same has initial state
console.log("~ Tags: ",userTags.length);
// *** ATTEMPT TO SAVE DATA
profileData.tags = [...userTags];
console.log("- After: ",profileData.tags.length);
};
},[])
);
const handdleTagRemoval = (tagName: string) => {
// *** REMOVE SELECTED ITEM,DONE USING ARRAY.FILTER
console.log("Remove tag");
const tags = [...userTags];
const filteredTags = tags.filter((tagItem) => tagItem.name !== tagName);
// profileData.tags = filteredTags;
setUserTags(filteredTags);
console.log("~",tagName," was removed");
console.log(userTags.length," are left");
};
};
解决方法
按@Drew Reese的建议通过添加userTags
作为依赖项来解决。这意味着我要额外使用两次此钩子。
useFocusEffect(
// Fetch Tag Data
React.useCallback(() => {
console.log("----------------");
console.log("Tag data fetched");
console.log("----------------");
const tagData = [...profileData.tags];
setUserTags(tagData);
console.log("- Before: ",userTags.length);
},[])
);
useFocusEffect(
// Save changes
React.useCallback(() => {
console.log("----------------");
console.log("Save changes");
console.log("----------------");
console.log("~ Tags: ",[userTags])
);
useFocusEffect(
// Post final changes
React.useCallback(() => {
return () => {
// Save Final changes
console.log("----------------");
console.log("Post changes");
console.log("----------------");
console.log("~ Post Tags: ",userTags.length);
profileData.tags = [...userTags];
console.log("- After: ",profileData.tags.length);
};
},[userTags])
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。