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

就像标题说的那样,我设置的 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]);
stack overflow Why is localStorage getting cleared whenever I refresh the page?
原文答案
author avatar

接受的答案

当您重新加载应用程序/组件时,两个效果都会运行,并且 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


答案:

作者头像

The above solution does not work in all cases. Instead add a conditional in front of the localStorage.setItem line in order to prevent the [] case.

//does not work in all cases (such as localhost)
function TodoList() {
  const [todoList, setTodoList] = useState(() => {
    return JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
  });
//use conditional instead
 useEffect(() => {
    if (todoList.length > 0) {localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todoList))}
  }, [todoList])