React中实现页面加载时将页面ID存入localStorage数组(去重)
问题:页面加载时将唯一页面ID存入localStorage数组
我希望用户每次加载页面时,把当前页面ID存入localStorage的数组里,只有当该ID不在数组中时才添加。但我试了自己写的代码,新页面加载时数组根本不更新,永远只保留第一个页面ID,试了好几种方法都没解决,求帮忙。
最初尝试的代码
const [isPostId, setItems] = useState([postId]); useEffect(() => { // const items = JSON.parse(localStorage.getItem('items')); if (JSON.parse(localStorage.getItem('isPostId')) == null) { localStorage.setItem('isPostId', JSON.stringify(isPostId)); } if (!isPostId.includes(postId)) { JSON.parse(localStorage.getItem('isPostId')) localStorage.setItem('isPostId', JSON.stringify(isPostId)); } }, [isPostId]);
问题解决说明
编辑:问题已解决,之前是对localStorage的工作机制存在误解,感谢大家的帮助。
以下两种代码均可正常运行:
方案一
useEffect(() => { const storageKey = "isPostId"; const json = localStorage.getItem("isPostId"); const previousPosts = json ? JSON.parse(json) : []; const filtered = previousPosts.filter((it) => it !== postId); const updatedPosts = [...filtered, postId]; const stringifyed = JSON.stringify(updatedPosts); localStorage.setItem('isPostId', stringifyed); console.log('heu',filtered) }, [])
方案二
useEffect(() => { // options a - 完全替换 localStorage.setItem('isPostId', JSON.stringify(isPostId)); // option b - 仅添加唯一ID,不删除已有项 var currentIds = JSON.parse(localStorage.getItem('isPostId')) || []; isPostId.map((e) => { if (!currentIds.includes(e)) { currentIds.push(e); } }) localStorage.setItem('isPostId', JSON.stringify(currentIds)); }, [isPostId])
内容的提问来源于stack exchange,提问作者jean eude
相关产品推荐
相关产品推荐

