当前位置: 首页 > news >正文

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}
        </>
    )
}
http://www.dtcms.com/a/65101.html

相关文章:

  • 从需求文档到测试点:基于 OCR 和智能接口的高效图片信息提取与分析
  • C++面向对象——继承学习笔记
  • 用AI写小说-小白写小说的第一步Prompt
  • HTML中修改标题和段落的第三种方式——外部样式表
  • 【安卓逆向】安卓病毒介绍及其简单案例分析
  • 解决VMware虚拟机CentOS 7 忘记登陆密码问题
  • API接口安全中的数据加密实践:原理与实现详解
  • 【Java】——数据类型和变量
  • JAVA代码块
  • visual studio配置opencv
  • 【后端开发面试题】每日 3 题(十一)
  • 【linux】解决 Linux 系统中 root 用户无法打开图形界面问题
  • Python 的字符串格式化方法
  • 编程助手学Python--Deepseek对OpenAI的Python库调用GPT-4模型生成对话回复理解
  • docker 常用命令大全(二),docker 镜像操作 ,持续更新
  • 仅仅使用pytorch来手撕transformer架构(1):位置编码的类的实现和向前传播
  • 系统架构设计师知识小科普:系统架构评估
  • 【文献阅读】SPRec:用自我博弈打破大语言模型推荐的“同质化”困境
  • Linux上位机开发实战(qt编译之谜)
  • vue 仿deepseek前端开发一个对话界面
  • 3分钟复现 Manus 超强开源项目 OpenManus
  • 使用netlify部署github的vue/react项目或本地的dist,国内也可以正常访问
  • 人工智能混合编程实践:Python ONNX进行图像超分重建
  • PyTorch 和 Python关系
  • 先进制造aps专题三十一 免费企业高级计划和优化(Advanced Planning and Optimizer)产品FreeAPO简介
  • ELK traceId实现跨服务日志追踪
  • 【MySQL】MySQL程序解析
  • Leetcode 95-不同的二叉搜索树 II
  • Python----计算机视觉处理(opencv:像素,RGB颜色,图像的存储,opencv安装,代码展示)
  • 当量子计算遇上互联网安全:挑战与革新之路