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

Why is localStorage getting cleared whenever I refresh the page?

正如标题所说,我设置的 localStorage 记录了对 todoList 数组所做的更改并 JSON.stringifys 它;但是,每当我刷新页面时,数组 returns 到默认的 [] 状态。

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]);

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

示例:

const LOCAL_STORAGE_KEY = "task-list"

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

  ...