jpc*_*eia 4 local-storage typescript next.js react-hooks
我正在尝试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;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = (value) => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
Run Code Online (Sandbox Code Playgroud)
但是,当我在 NextJS 中使用它时,它会生成以下错误:
未捕获错误:水合失败,因为初始 UI 与服务器上呈现的内容不匹配
经过一番搜索后,我发现该window对象在(Next.js)服务器端不存在,这是错误的可能原因(Window is not Defined in Next.js React app)。一个可能的解决方案是保护仅在客户端运行的钩子window的使用。useEffect
我当前的钩子实现useLocalStorage是
function useLocalStorage<T>(key: string, defaultValue: T): [T, Dispatch<SetStateAction<T>>] {
const [value, setValue] = useState<T>(defaultValue);
useEffect(() => {
try {
const item = window.localStorage.getItem(key);
setValue(item ? JSON.parse(item) : defaultValue);
}
catch (error) {
setValue(defaultValue);
}
}, [key, defaultValue]);
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};
Run Code Online (Sandbox Code Playgroud)
但是,这次挂钩并不总是按预期工作,因为无法保证 useEffect 回调的执行顺序。结果,有时状态会丢失。
我想知道 NextJS 中的正确实现是什么,并了解我的代码逻辑在哪里失败。
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
export default function useLocalStorage<T>(
key: string,
defaultValue: T
): [T, Dispatch<SetStateAction<T>>] {
const isMounted = useRef(false)
const [value, setValue] = useState<T>(defaultValue)
useEffect(() => {
try {
const item = window.localStorage.getItem(key)
if (item) {
setValue(JSON.parse(item))
}
} catch (e) {
console.log(e)
}
return () => {
isMounted.current = false
}
}, [key])
useEffect(() => {
if (isMounted.current) {
window.localStorage.setItem(key, JSON.stringify(value))
} else {
isMounted.current = true
}
}, [key, value])
return [value, setValue]
}
Run Code Online (Sandbox Code Playgroud)
在这里,useRef用于防止defaultValue在第一次渲染中存储localStorage。基本上,它会跳过第二个回调useEffect以在第一个渲染上运行,因此初始化可以通过第一个useEffect钩子在没有竞争条件的情况下完成。
| 归档时间: |
|
| 查看次数: |
7490 次 |
| 最近记录: |