我正在尝试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)