英文:
Favourite list on LocalStorage with React JS
问题
我已经使用LocalStorage创建了一个收藏夹列表,但每次重新加载页面时都会添加一个项目。这些元素来自JSON。
以下是我的代码如何运作的示例:https://www.codesandbox.io/s/intelligent-wood-d9y4zw?file=/src/App.js
const [storageItem, setStorageItem] = useState(() => JSON.parse(localStorage.getItem("favourites") || "[]"))
const isFavourited = storageItem.includes(blok._uid)
const handleToggleFavourite = () => {
if (!isFavourited) {
const newStorageItem = [...storageItem, blok._uid]
setStorageItem(newStorageItem);
localStorage.setItem("favourites", JSON.stringify(newStorageItem))
} else {
const newStorageItem = storageItem.filter((savedId) => savedId !== blok._uid)
setStorageItem(newStorageItem);
localStorage.setItem("favourites", JSON.stringify(newStorageItem))
}
}
英文:
I have created a favourite list with LocalStorage, but it adds one item at a time each time I reload the page. The elements are taken from a JSON
Here is an example of how my code works: https://www.codesandbox.io/s/intelligent-wood-d9y4zw?file=/src/App.js
const [ storageItem, setStorageItem ] = useState(() => JSON.parse(localStorage.getItem("favourites") || "[]" ))
const isFavourited = storageItem.includes(blok._uid)
const handleToggleFavourite = () => {
if (!isFavourited) {
const newStorageItem = [...storageItem, blok._uid]
setStorageItem(newStorageItem);
localStorage.setItem("favourites", JSON.stringify(newStorageItem))
} else {
const newStorageItem = storageItem.filter((savedId) => savedId !== blok._uid)
setStorageItem(newStorageItem);
localStorage.setItem("favourites", JSON.stringify(newStorageItem))
}
}
答案1
得分: 0
你需要检查你调用方法的位置,因为看起来你是在一个 useEffect 或类似的地方这样做的,这就是为什么在重新加载页面时添加了该项。
英文:
you need to check where you are calling the method because it seems you are doing it in a useEffect or something like that and that’s why add the item when you reload the page
答案2
得分: 0
你在映射对象时使用了useState
。useState
钩子只能在函数组件的最顶层使用。
我已经稍微修复了一下,这是新的更新后的URL:https://codesandbox.io/s/wonderful-lederberg-97fy54?file=/src/App.js。
英文:
Well, you were using useState
when mapping an object. Hooks useState
can only be used in the topmost level of a functional component.
I've fixed a bit here is the new updated URL <https://codesandbox.io/s/wonderful-lederberg-97fy54?file=/src/App.js>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论