简体   繁体   English

如何将当前的state设置为useState hook?

[英]How to set the current state to the useState hook?

I have a state to keep track when a SubMenu is opened, and toggle it when another Menu Item is clicked.我有一个 state 来跟踪打开子菜单的时间,并在单击另一个菜单项时切换它。 It goes like this:它是这样的:

    const [open, setOpen] = useState();
    const toggle = (id) => setOpen(id);

    onClick={() => toggle(item.navId)}

When I click the refresh button in the browser, the current Sub Menu that is opened, closes.当我单击浏览器中的刷新按钮时,当前打开的子菜单关闭。 I believe it is because the initial state is empty.我相信这是因为最初的 state 是空的。 How can I keep the current Sub Menu opened after the page is reloaded/refreshed.如何在页面重新加载/刷新后保持当前子菜单打开。 I've been looking around and I am really not sure if I should use prevState or how to implement it to my case.我一直在环顾四周,我真的不确定我是否应该使用prevState或如何根据我的情况实施它。 Any tips or pointing a direction to a solution is much appreciated.非常感谢任何提示或指向解决方案的方向。 Thanks.谢谢。

You need to persist the data when the browser is refreshed.您需要在浏览器刷新时持久化数据。 As others stated using LocalStorage is a good option.正如其他人所说,使用 LocalStorage 是一个不错的选择。 I always use a custom hook I wrote for such cases:我总是使用我为这种情况编写的自定义钩子:

import { useEffect, useRef, useState } from 'react';

export function useLocalStorage(key, defaultValue) {
  const [state, setState] = useState(() => {
    const valueInLocalStorage = window.localStorage.getItem(key);
    if (valueInLocalStorage) {
      return JSON.parse(valueInLocalStorage);
    }
    return defaultValue;
  });

  const prevKeyRef = useRef(key);

  useEffect(() => {
    const prevKey = prevKeyRef.current;
    if (prevKey !== key) {
      window.localStorage.removeItem(prevKey);
    }
    prevKeyRef.current = key;
    window.localStorage.setItem(key, JSON.stringify(state));
  }, [key, state]);

  return [state, setState];
}

You can then import it and use it然后您可以导入并使用它

import { useSessionStorage } from 'hooks/uselocalStorage';
const [open, setOpen] = useSessionStorage(storageKey, initialConfig);

When you hit the refresh button of the browser, your state will take its initial value, null in your case because you are not passing anything.当您点击浏览器的刷新按钮时,您的 state 将采用其初始值,在您的情况下为null因为您没有传递任何内容。 prevState will have the same behaviour. prevState将具有相同的行为。 localStorage can be a solution. localStorage可以是一个解决方案。

You could add a query parameter for the opened sub menu.您可以为打开的子菜单添加查询参数。 URL might look something like this: www.test.com/menu?nav=1 . URL 可能看起来像这样: www.test.com/menu?nav=1 ?nav=1。 Then you could read the value of nav and use that for the initial state.然后您可以读取nav的值并将其用于初始 state。

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

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