如何在React应用程序中刷新浏览器时将本地存储项值加1

问题描述 投票:0回答:2

在我的 React 应用程序中,当您刷新浏览器时,我必须将

count
值更新/增加
1
。我也想将这个
count
存储在localStorage中。

我该如何处理这个问题?

首先我有这样的事情:

 const initialCount = () => {
  if (typeof window !== 'undefined' && hasRedirectQueryParam) {
   return Number(window.localStorage.getItem('count')) || 0;
  }
   return null;
  };

 const [count, setCount] = useState(initialCount);

 useEffect(() => {
   setCount(count);
   window.localStorage.setItem('count', String(initialCount()));
  }, []);

但是现在我该如何使用

setCount
呢?那么当浏览器刷新时
count
会增加
1

使用 React useState 和 useEffect 挂钩的正确 React 实现是什么?

reactjs react-hooks local-storage react-typescript
2个回答
0
投票

你不应该使用反应状态。只需从本地存储读取计数并在应用程序启动时更新该值(例如在 app.js 文件内但在组件外部)。


0
投票

我想这就是你想要的。您可以如下所示定义initialCount函数,以便可以提升它。您应该在依赖项数组中添加数字,以便最新的值将保留在本地存储中。


const App = () => {
  const [count, setCount] = useState(initialCount);

  function initialCount() {
    const isLocalStorageAvailable =
      typeof window !== "undefined" && window.localStorage;

    return isLocalStorageAvailable
      ? Number(window.localStorage.getItem("count")) || 0
      : 0;
  }

  useEffect(() => {
    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  function handleBeforeUnload() {
    setCount((prev) => {
      const count = prev + 1;
      window.localStorage.setItem("count", String(count));
      return count;
    });
  }
  
  return (
    <>
      <h1>Hello World!</h1>
      <p>Count: {count}</p>
    </>
  );
};

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.