小编Ale*_*drs的帖子

在 NextJS 中反应自定义 localstorage hook 水合错误

我试图localstorage在 NextJS 中实现钩子,但出现以下错误:Error: Hydration failed because the initial UI does not match what was rendered on the server.。有什么想法可能导致它吗?在我看来,该功能似乎useEffect没有正确使用。如何强制使用 CSR 而不是 SSR 以避免水合错误?

import { useState, useEffect } from 'react';

function useLocalStorage<T>(key: string, initialValue: T) {
    const [storedValue, setStoredValue] = useState<T>(() => {
        if (typeof window === 'undefined') {
            return initialValue;
        }
        try {
            const item = window.localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            return initialValue;
        }
    });

    useEffect(() => { …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs next.js

5
推荐指数
1
解决办法
4373
查看次数

标签 统计

javascript ×1

next.js ×1

reactjs ×1

typescript ×1