我正在使用React和TypeScript编写一个todo应用程序。我正在使用localStorage来获得我想要的持久性。
让我给你看一些代码。
const [todos, setTodos] = useState<todoModel[]>([]);
useEffect(() => {
localStorage.setItem("todoItem", JSON.stringify(todos));
}, [todos])
const storesTodos = () => {
const storedValues = localStorage.getItem("todoItem");
if(!storedValues) { return todos; }
return JSON.parse(storedValues);
}
useEffect(() => { getToDoList(); storesTodos();
console.log("default") }, [])
useEffect(() => {
if (!props.reload) return;
console.log(props.reload)
getToDoList();
storesTodos();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.reload])
我正在将StoresTodo()
函数添加到我的useEffects中,我尝试了这两个函数。但这行不通。我将数据放入本地存储,但当重新加载页面时,它会返回到默认值。
我在这里错过了什么?
您似乎得到了相同的初始值,因为您从未根据共享代码更新todos
。
你可以做这个
...
const storesTodos = () => {
const storedValues = localStorage.getItem("todoItem");
if(!storedValues) {
setTodos(todos)
return todos;
}
return JSON.parse(storedValues);
}
或者你可以从这里使用本地存储状态挂钩
function useLocalStorageState({
key,
initialValue,
serialize = v => v,
deserialize = v => v,
}) {
const [state, setState] = React.useState(
() => deserialize(window.localStorage.getItem(key)) || initialValue,
)
const serializedState = serialize(state)
React.useEffect(() => {
window.localStorage.setItem(key, serializedState)
}, [key, serializedState])
return [state, setState]
}
刷新页面时,甚至在中设置useEffect之前
const [todos, setTodos] = useState<todoModel[]>([]);
已经将您的初始todos数组设置为空数组。
也许你需要像一样对localStorage进行检查
const [todos, setTodos] = useState<todoModel[]>(() => {
const storedValues = localStorage.getItem("todoItem");
return storedValues ? JSON.parse(storedValues) : [];
});