Favourite list on LocalStorage with React JS 在React JS中使用LocalStorage的收藏列表

huangapple go评论56阅读模式
英文:

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

你在映射对象时使用了useStateuseState钩子只能在函数组件的最顶层使用。

我已经稍微修复了一下,这是新的更新后的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>

huangapple
  • 本文由 发表于 2023年7月11日 00:36:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定