小编jpc*_*eia的帖子

如何在 Next.js 中实现 useLocalStorage 挂钩?

我正在尝试useState在 next.js 中创建一个能够适应页面刷新的替代品。

遇到的可能解决方案之一是使用window.localStorage来保存和检索状态。即使页面刷新后,这也会使状态保持不变。

我发现了以下useLocalStorageReactJS 钩子的实现https://usehooks.com/useLocalStorage/

function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    if (typeof window === "undefined") {
      return initialValue;
    }
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue; …
Run Code Online (Sandbox Code Playgroud)

local-storage typescript next.js react-hooks

4
推荐指数
1
解决办法
7490
查看次数

标签 统计

local-storage ×1

next.js ×1

react-hooks ×1

typescript ×1