gpt4 book ai didi

reactjs - 为什么每次刷新页面时 localStorage 都会被清除?

转载 作者:行者123 更新时间:2023-12-05 01:23:35 34 4
gpt4 key购买 nike

如标题所说,我设置的 localStorage 注册了对 todoList 数组所做的更改,并对其进行了 JSON.stringify;但是,每当我刷新页面时,数组都会返回到默认的 [] 状态。

const LOCAL_STORAGE_KEY = "task-list"

function TodoList() {
const [todoList, setTodoList] = useState([]);

useEffect(() => {
const storedList = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (storedList) {
setTodoList(storedList);
}
}, []);

useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
}, [todoList]);

最佳答案

当您重新加载应用程序/组件时,两种效果都会运行,并且 React 状态更新是异步处理的,因此它会在处理状态更新之前获取持久保存到 localStorage 的空数组状态。设置初始todoList状态值时直接从localStorage中读取即可。

例子:

const LOCAL_STORAGE_KEY = "task-list"

function TodoList() {
const [todoList, setTodoList] = useState(() => {
return JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
});

useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList));
}, [todoList]);

...

Edit why-is-localstorage-getting-cleared-whenever-i-refresh-the-page

关于reactjs - 为什么每次刷新页面时 localStorage 都会被清除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72222728/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com