繁体   English   中英

React:页面刷新时如何存储数组

[英]React: How to store array when the page refreshes

我在 React 中有一个数组,将使用useEffect显示。 那东西从前一个组件到下一个组件。 现在,我使用useEffect useState数组。 但是当我刷新页面时,数组变得未定义并且页面变为空白。 如何再次获取数组,以便即使我重新加载页面也不会引发错误。

我使用过sessionStoragelocalStorage 但没有什么对我有用。

这是我到目前为止所做的代码:

const location = useLocation();
useEffect(() => {
        console.log(location.groupsname);
        sessionStorage.setItem('groups', JSON.stringify(location.groupsname));
        const a = JSON.parse(sessionStorage.getItem('groups'));
        console.log(a);
        setimportedgroups(a);
    }, []);

我应该如何解决? 谢谢你。

问题

你很亲密。 这里的问题是,当组件再次挂载时,您正在清除所有保存的存储值。

useEffect(() => {
  // setting storage is synchronous
  sessionStorage.setItem('groups', JSON.stringify(location.groupsname));
  // getting the value just set
  const a = JSON.parse(sessionStorage.getItem('groups'));
  console.log(a);
  setimportedgroups(a);
}, []);

如果在页面重新加载时location.groupsname未定义,那么这就是存储的内容并从存储中加载回来。

解决方案

You'll want to use a state initializer function and two useEffect hooks, 1 to persist to storage local state when it updates, and a second to update local state when the location groupsname updates and has a defined value.

const location = useLocation();

// initialize state from storage on mount
const [importedGroups, setImportedGroups] = useState(() => {
  const groups = sessionStorage.getItem('groups');
  return JSON.parse(groups) ?? {};
});

// persist importedGroups state to storage
useEffect(() => {
  sessionStorage.setItem('groups', JSON.stringify(importedGroups));
}, [importedGroups]);

// update local state when location.groupsname updates
useEffect(() => {
  if (location.groupsname) {
    setImportedGroups(location.groupsname);
  }
}, [location.groupsname]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM