目录

nextJs在DOM视图中渲染未转为状态值的localStorage导致报错

目录

nextJs在DOM视图中渲染未转为状态值的localStorage导致报错

报错但不限于如下:

error: hydration failed because the initial ui does not match what was rendered on the server.

Did not expect server HTML to contain a <span> in <div>.

hook.js:608 warning: expected server html to contain a matching <img> in <span>.

Unhandled Runtime Error[](https://nextjs.org/docs/messages/react-hydration-error "Go to related documentation")[](https://nextjs.org/docs/app/building-your-application/configuring/debugging#server-side-code "Learn more about enabling Node.js inspector for server code with Chrome DevTools") Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:

问题代码:

"use client"

import * as React from "react"

export default function Page() {

    let msg = ""
    if (typeof window !== 'undefined') {
        msg = window.localStorage.getItem("msg") ?? ""
    }

    return (
        <>
            <h1>demo page</h1>
            {msg}
        </>
    )
}

正确代码

"use client"
import * as React from "react"

export default function Page() {

    const [msg, setMsg] = React.useState("")

    React.useEffect(() => {
        setMsg(window.localStorage.getItem("msg") ?? "")
    }, [])

    return (
        <>
            <h1>demo page</h1>
            {msg}
        </>
    )
}