【发布时间】: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
【问题讨论】:
-
因为
next在服务器上运行,但是localstorage只能在浏览器中使用 -
useLocalStorage是从图书馆导入的吗?您是否正在尝试从服务器上的localStorage访问值?参见Next.js Pre-rendering。
标签: reactjs react-hooks next.js static-site-generation