简体   繁体   English

为什么使用 Next.js 中的表会引发水合作用错误?

[英]Why is using a table in Next.js throwing a hydration error?

In this code, I have a problem on using tag.在此代码中,我在使用标签时遇到问题。 when I use tr tag the error occurs.It says that Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server.当我使用 tr 标记时发生错误。它说未处理的运行时错误错误:水化失败,因为初始 UI 与服务器上呈现的内容不匹配。

import React from 'react'
import {useState} from 'react'


const port = () => {
  return (
    <div className="ml-14">
      <div className="profile">
        <h1 className="mt-5 font-bold">Nasvirat</h1>
        <p className="mt-5">total balance : </p>
      </div>
      <div className="portfolio">
        <h2 className="mt-7">Holding</h2>

        <table>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
        </tr>
        <tr>
          <td>Peter</td>
          <td>Griffin</td>
        </tr>
        <tr>
          <td>Lois</td>
          <td>Griffin</td>
        </tr>
        </table>
      </div>
    </div>
  )
}

export default port

do u have idea why this happen and how to fix it.你知道为什么会发生这种情况以及如何解决它吗?

This is an open issue in the Next.js repo.这是Next.js库中的未决问题 The issue is coming from the fact that you do not have <tbody> or <thead> wrapping your rows.问题来自于您没有<tbody><thead>包装您的行。

Although they are not specified to mandatory for correctly rendering the table, next.js somehow cannot identify this.尽管它们没有被指定为正确呈现表格所必需的, next.js不知何故无法识别这一点。

My assumption is there is a difference in the code that is run on the server and on the client because of this.我的假设是,因此在服务器和客户端上运行的代码存在差异。

Try adding this:尝试添加这个:

        <table>
        <tbody>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
        </tr>
        <tr>
          <td>Peter</td>
          <td>Griffin</td>
        </tr>
        <tr>
          <td>Lois</td>
          <td>Griffin</td>
        </tr>
        </tbody>
        </table>

It is noteworthy, that browsers add a tbody inside the table automatically .值得注意的是,浏览器会自动table中添加一个tbody So even if you skip it, it will end up in your DOM code.所以即使你跳过它,它最终也会出现在你的 DOM 代码中。 This is for older HTML versions as mentioned in the answer.如答案中所述,这是针对较旧的 HTML 版本。 Here is a demo for that.这是一个演示 Check the code and compare it with the actual DOM that is rendered.检查代码并将其与呈现的实际 DOM 进行比较。

I am guessing next.js does not add the tbody by default when generating on server side.我猜next.js在服务器端生成时默认不添加tbody This is what causes the mismatch.这就是导致不匹配的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM