简体   繁体   English

接下来如何解决 React Hydration 错误

[英]How To Solve React Hydration Error in Next

I keep getting an error saying "Hydration failed because the initial UI does not match what was rendered on the server."我不断收到一条错误消息,提示“水合失败,因为初始 UI 与服务器上呈现的内容不匹配。”

I have no idea what is causing the error so I was hoping someone else may know what is wrong.我不知道是什么导致了错误,所以我希望其他人可能知道出了什么问题。 I think I narrowed down where the error is happening and posted the code below of where I think it breaks.我想我缩小了错误发生的范围,并在下面发布了我认为它中断的代码。 If any more code is needed let me know.如果需要更多代码,请告诉我。

Thanks in advance for all the help.提前感谢所有帮助。

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;

I think you probably missed tbody in table, that will cause this error in nextjs.我认为您可能错过了表格中的 tbody,这将导致 nextjs 中出现此错误。 Try尝试

      <table>
       <tbody>
        <tr>
          <th>Coin</th>
          <th>Price</th>
          <th>24h</th>
        </tr>
        {coins.map((coin: any, index: any) => (
          <Coin key={index} coin={coin} />
        ))}
        </tbody>
      </table>

If you want to suppress a hydration warning on a given component, you can pass the suppressHydrationWarning prop to it.如果要抑制给定组件上的水合警告,可以将suppressHydrationWarning属性传递给它。

This signals to React that the component's content may be different once the page is re-rendered on the client-side and to ignore the error.这向React发出信号,一旦页面在客户端重新渲染,组件的内容可能会有所不同,并忽略错误。

<Coin key={index} coin={coin} suppressHydrationWarning />

See Suppress Hydration Warning (React Docs) :请参阅抑制水合警告(React Docs)

If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element.如果你将 suppressHydrationWarning 设置为 true,React 不会警告你该元素的属性和内容不匹配。 It only works one level deep, and is intended to be used as an escape hatch.它只工作一层深,旨在用作逃生舱口。 Don't overuse it.不要过度使用它。 You can read more about hydration in the ReactDOM.hydrateRoot() documentation.您可以在 ReactDOM.hydraRoot() 文档中阅读有关水合作用的更多信息。

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

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