刷新页面时清除上下文值(来自状态)

Context value (coming from state) gets cleared while refreshing the page

我有一个 React 应用程序,我在其中使用上下文 API 作为状态管理。我从服务器获取特定值,将其分配给组件状态,然后将其存储为上下文值。但是,问题是每当页面刷新和重新加载时,上下文值都会随着上述状态丢失而被清除。即使页面重新加载,是否有办法存储和保留此值?除了本地存储还有什么办法吗?

非常感谢任何帮助。

当您清除浏览器页面时,您最终清除了与该页面相关的所有数据(不包括 localStorage 和缓存数据)。

因此您需要在接收数据时或关闭页面前使用本地存储。

此外,对于某些任务,您可以在浏览器中使用 DB 来存储复杂数据

下面的示例是一个自定义挂钩,它使用存储 API 来获取和保存值。它的工作方式类似于 useState 挂钩,但使用 keyName 字符串指定存储中的键名并设置值。

使用此挂钩允许您的上下文提供程序组件获取其值并将其永久保存在用户的设备上。

import { useState, useEffect } from 'react'

const useLocalStorage = keyName => {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(keyName);
    try {
      const parsedValue = JSON.parse(storedValue);
      return parsedValue;
    } catch(error) {
      return storedValue;
    }
  });

  useEffect(() => {
    const stringifiedValue = JSON.stringify(value);
    localStorage.setItem(keyName, stringifiedValue);
  }, [value]);

  return [value, setValue];
};

export default useLocalStorage

用法示例:

import useLocalStorage from './useLocalStorage';

const Component () => {
  const [value, setValue] = useLocalStorage('user');
  ...
};