[英]Why is using a table in Next.js throwing a hydration error?
在此代碼中,我在使用標簽時遇到問題。 當我使用 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
你知道為什么會發生這種情況以及如何解決它嗎?
這是Next.js
庫中的未決問題。 問題來自於您沒有<tbody>
或<thead>
包裝您的行。
盡管它們沒有被指定為正確呈現表格所必需的, next.js
不知何故無法識別這一點。
我的假設是,因此在服務器和客戶端上運行的代碼存在差異。
嘗試添加這個:
<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>
值得注意的是,瀏覽器會自動在table
中添加一個tbody
。 所以即使你跳過它,它最終也會出現在你的 DOM 代碼中。 如答案中所述,這是針對較舊的 HTML 版本。 這是一個演示。 檢查代碼並將其與呈現的實際 DOM 進行比較。
我猜next.js
在服務器端生成時默認不添加tbody
。 這就是導致不匹配的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.