正在构建useLocalStorage挂钩以允许存储Set变量



我试图修改此处的代码>useLocalStorage挂钩

这样我就可以将一个Set((保存到localStorage。

useLocalStorage.js

import { useState, useEffect } from "react";
// Hook
export const useLocalStorage = (key, initialValue) => {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") {
return initialValue;
}

try {
// Get from local storage by key
const item = JSON.parse(window.localStorage.getItem(key));
// Parse stored json or if none return initialValue
if(initialValue instanceof Set) {
return (item ? new Set([...item]) : initialValue);
} else {
return item ? item : initialValue
}
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
//const addValue = (value) => {
//    setStoredValue(prev => new Set(prev).add(value));
//};
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = (value) => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value;
if(valueToStore instanceof Set){
setStoredValue( new Set([...valueToStore]) );
} else {
setStoredValue(valueToStore);
}
// Save state
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
useEffect(() => {
// Save to local storage
if (typeof window !== "undefined") {
if(storedValue instanceof Set){
window.localStorage.setItem(key, JSON.stringify([...storedValue])); 
} else {
window.localStorage.setItem(key, JSON.stringify(storedValue));
}
}
}, [storedValue]);
return [storedValue, setValue /*,addValue */];
}

在我的React组件中,我试图根据以前的状态设置值。

reactComponent.js

const [itemUrlIdSet, setItemUrlIdSet] = useLocalStorage('itemUrlIdSet', new Set());
const addItemUrlIdToSet = (item) => setItemUrlIdSet(prev => new Set(prev).add(item));
useEffect(() =>
addItemUrlIdToSet(`text changes when props change`);
}, [props]);

如果我用addValue替换setValue,它工作得很好。。。Set in storedValue状态更新,localStorage更新。如果我使用setValue,storedValue实际上永远不会改变。

Add不太理想,有时我需要将我的Set((替换为一个完全新的、不基于上一个Set((的Set((。

我很困惑为什么它不适用于setValue。我不明白我做错了什么。

您是否尝试过功能更新而不是直接设置value

setStoredValue((prev) => new Set([...valueToStore]))

注意:这是我解决这个问题的方法。

好吧,我想我已经想通了。在reactComponent.js中,我这样调整了我的代码>

const addItemUrlIdToSet = (item) => setItemUrlIdSet(prev => new Set(prev).add(item));

到这个

const addItemUrlIdToSet = (item) => setItemUrlIdSet(prev => prev.add(item));

我认为发生的事情是对Set((的引用没有更新钩子内的State。我知道通常你不应该直接改变这种状态。我不确定是否有更好的方法。但它起作用了。

编辑:我还在useLocalStorage.js 中添加了@okapies建议的修改

setStoredValue((prev) => new Set([...valueToStore]) );

最新更新