【问题标题】:Why useLocalStorage does not work with Next.js?为什么 useLocalStorage 不适用于 Next.js?
【发布时间】:2022-12-03 23:24:29
【问题描述】:

这将引发 Error: Hydration failed because the initial UI does not match what was rendered on the server. 错误:

const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useLocalStorage<string>('teamId', undefined)

这不会:

const [selectedOrganizationShortId, setSelectedOrganizationShortId] =
useState<string>(undefined)
const [selectedProgramId, saveSelectedProgramId] = useState<
string | undefined
>(undefined)

虽然两者都一样。我会使用useLocalStorage,因为它是方便的解决方案,但它似乎与 Next.js 不兼容。

useLocalStorage 从这里使用:https://usehooks-ts.com/react-hook/use-local-storage

【问题讨论】:

标签: reactjs react-hooks next.js static-site-generation


【解决方案1】:

我的回答是针对您的需要的建议。

您可以为您的目的编写一个自定义挂钩,因此不需要任何外部库:

export function useLocalStorage<T>(key: string, fallbackValue: T) {
    const [value, setValue] = useState(fallbackValue);
    useEffect(() => {
        const stored = localStorage.getItem(key);
        setValue(stored ? JSON.parse(stored) : fallbackValue);
    }, [fallbackValue, key]);

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue] as const;
}

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2022-10-09
    • 2022-01-06
    • 1970-01-01
    • 2022-06-10
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多