接下来如何解决React水合错误

Aze*_*L87 4 html javascript reactjs next.js

我不断收到错误消息“水合失败,因为初始 UI 与服务器上呈现的内容不匹配。”

我不知道是什么导致了错误,所以我希望其他人可能知道出了什么问题。我想我缩小了错误发生的范围,并在下面发布了我认为错误的代码。如果需要更多代码,请告诉我。

预先感谢您的所有帮助。

import React, { useEffect } from "react";
import styles from "../../styles/Home.module.css";
import Coin from "../Coin/Coin";

type CoinListProps = {
  coins: any;
};

const CoinList = ({ coins }: CoinListProps) => {
  useEffect(() => {
    console.log(coins);
  }, []);

  return (
    <div className={styles.coinList}>
      <table>
        <tr>
          <th>Coin</th>
          <th>Price</th>
          <th>24h</th>
        </tr>
        {coins.map((coin: any, index: any) => (
          <Coin key={index} coin={coin} />
        ))}
      </table>
    </div>
  );
};

export default CoinList;

Run Code Online (Sandbox Code Playgroud)

GRO*_*ER. 5

如果您想抑制给定组件上的水合警告,您可以将suppressHydrationWarningprop 传递给它。

\n

这表明一旦页面在客户端重新呈现,React组件的内容可能会有所不同,并忽略该错误。

\n
<Coin key={index} coin={coin} suppressHydrationWarning />\n
Run Code Online (Sandbox Code Playgroud)\n

请参阅抑制水合警告(React 文档)

\n
\n

如果你将suppressHydrationWarning设置为true,React不会警告你该元素的属性和内容不匹配。它只能工作一层深度,旨在用作逃生舱口。不要过度使用它。您可以在 ReactDOM.HydrateRoot() 文档中阅读有关水合的更多信息。

\n
\n