我最近正在尝试学习tanstack table v8 React table。
它正确呈现表中的列和数据,但是我收到一条错误消息 “水合失败,因为初始 UI 与服务器上呈现的内容不匹配” “警告:预计服务器 HTML 中包含匹配项。”
我还检查了表格的结束标签,但它是正确的
代码:
"use client";
import {
useReactTable,
getCoreRowModel,
flexRender,
} from "@tanstack/react-table";
import { useMemo } from "react";
const Table = ({ data, columns }) => {
const dataTable = useMemo(() => data, [data])
const table = useReactTable({
data: dataTable,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div>
BasicTable
<table>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Table;
当服务器和客户端组件不匹配时,就会发生水合。在本例中,您尝试将数据传递到 Table 组件,但数据本身在客户端未定义或为 null。您可以根据下一个js文档在导入表时禁用SSR,或者您可以简单地添加如下示例的代码。
import React, { useState, useEffect } from 'react';
export function App(props) {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
if (isClient) {
return (
<div className='App'>
<h1>Hello React.</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}