next.js 即使在将函数添加到useEffect [重复]后仍出现水合错误

fbcarpbf  于 2023-06-29  发布在  其他
关注(0)|答案(2)|浏览(146)

此问题已在此处有答案

Warning: Text content did not match. Server: "I'm out" Client: "I'm in" div(5个答案)
5天前关闭。
使用下一个13和制作一个导航菜单,显示当前的日期和时间,我得到水化错误,虽然该组件是一个客户端组件,也是使用useEffect

### /src/components/navigation/index.tsx

'use client'

import Link from 'next/link'
import React, { useEffect, useState } from 'react'

export default function Navigation() {
  // Time
  const [time, setTime] = useState(new Date().toLocaleTimeString())

  useEffect(() => {
    const locale = 'en'

    const updateFormattedTime = () => {
      const today = new Date()
      const formattedTime = today.toLocaleTimeString(locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric',
        hour: 'numeric',
        hour12: true,
        minute: 'numeric',
        timeZone: 'Asia/Kolkata'
      })
      setTime(formattedTime)
    }
    updateFormattedTime()

    const timer = setInterval(() => {
      updateFormattedTime()
    }, 60000)

    return () => {
      clearInterval(timer)
    }
  }, [])

  return (
    <div className="navigation">
      <Link href="/" className="head animate">
        OUTDATED
      </Link>
      <Link href="/information" className="head animate">
        Information
      </Link>
      {time && <p className="information red">{time.replace(/\//g, ',')}</p>}
    </div>
  )
}

它基本上只是获取日期和时间,并将其推到一个状态,并将其显示在头部本身。然后把斜线换成逗号
extact错误消息

Error: Text content does not match server-rendered HTML.

Warning: Text content did not match. Server: "5:43:50 PM" Client: "5:43:51 PM"

See more info here: https://nextjs.org/docs/messages/react-hydration-error
axzmvihb

axzmvihb1#

水化会使零部件渲染两次。一次在预渲染中,一次在浏览器渲染中。导致setInterval运行两次。
解决此问题的一种方法是在导入此组件时禁用ssr

import dynamic from 'next/dynamic'
const Navigation = dynamic(() => import('@/components/navigation'), {
  ssr: false,
})
xggvc2p6

xggvc2p62#

尝试suppressHydrationWarning,这应该可以解决水合问题

相关问题