【问题标题】:React-tooltip and Next.js SSR issueReact-tooltip 和 Next.js SSR 问题
【发布时间】:2021-01-12 16:29:05
【问题描述】:

我在 Next.js 应用程序中使用 react-tooltip 库。

我注意到每次我在访问使用工具提示的页面时刷新网站时都会收到错误消息:

react-dom.development.js:88 Warning: Prop `dangerouslySetInnerHTML` did not match.

客户端和服务器端的 CSS 类不同

奇怪的是,从随机页面导航到使用 react-tooltip 的页面时,我没有收到该错误。

tooltip相关代码:

<StyledPopularityTooltipIcon src="/icons/tooltip.svg" alt="question mark" data-tip="hello world" />
<ReactTooltip
    effect="solid"
    className="tooltip"
    backgroundColor="#F0F0F0"
    arrowColor="#F0F0F0"
    clickable={true}
/>

【问题讨论】:

    标签: css reactjs next.js server-side-rendering


    【解决方案1】:

    如果您使用任何服务器端渲染(如 Next.js) - 您需要确保在显示 react-tooltip 之前先安装您的组件。

    我使用以下方法解决了这个问题:

    import React, { useEffect, useState } from 'react';
    
    const [isMounted,setIsMounted] = useState(false); // Need this for the react-tooltip
    
    useEffect(() => {
        setIsMounted(true);
    },[]);
     
    return (<div>
          {isMounted && <ReactTooltip id={"mytip"} effect={"solid"} />}
    
          <span data-tip={"Tip Here"} data-for={"mytip"}>Hover me</span>
    </div>)
    

    【讨论】:

      【解决方案2】:

      您应该将 JSX 包装在以下组件中:

      import React, { useEffect, useState } from 'react';
      
      const NoSsr: React.FC = ({ children }) => {
        const [isMounted, setMount] = useState(false);
      
        useEffect(() => {
          setMount(true);
        }, []);
      
        return <>{isMounted ? children : null}</>;
      };
      
      export default NoSsr;
      

      像这样:

      <NoSsr>
       <YourJSX />
      </NoSsr>
      

      【讨论】:

      • 这是具有可重用组件的更清洁的解决方案,这应该是公认的答案。
      【解决方案3】:

      我遇到了同样的问题,我必须使用 state 来检测组件何时安装,然后才显示工具提示。

      附:导航时看不到错误,因为导航时页面没有在服务器上呈现,都是前端:)

      【讨论】:

      • @lemurry 你能提供示例代码吗?如果组件已安装,您是如何检测的?
      • @FabianBosler 您可以使用仅在第一次渲染时执行的 useState 和 useEffect 来实现。 codesandbox.io/s/brave-rosalind-4bb4v?file=/src/App.js如果您需要进一步解释,请告诉我。
      猜你喜欢
      • 2021-08-14
      • 2019-12-27
      • 2017-08-21
      • 1970-01-01
      • 2021-11-19
      • 2021-07-05
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多