【问题标题】:Gatsby 1 Class ComponentGatsby 1 类组件
【发布时间】:2020-04-20 03:01:10
【问题描述】:

我正在尝试理解布局中名为 AppMounted 的组件的逻辑 (Gatsby 1)

import { Component } from 'react';

export default class AppMounted extends Component {
  componentDidMount() {
    /* eslint-disable no-undef */

    // If the body element does not yet contain the "app-mounted" class
    if (!document.body.classList.contains('app-mounted')) {
      // Wait just a little longer
      setTimeout(() => {
        // And then add it
        document.body.classList.add('app-mounted');
      }, 50);
    }
    /* eslint-enable no-undef */
    // 50
  }

  render() {
    return null;
  }
}

然后是正文的scss样式

body {
    visibility: hidden;
        &.app-mounted {
            visibility: visible;
       }
}

据我了解,这将等待所有 50 毫秒以加载组件/数据然后显示它们。但如果没有这个组件,一切也都可以完美运行。问题是它在 Gastby 2 上造成了麻烦并隐藏了一切。通过在 Gastby 2 版本中取出它,一切都恢复正常了。有什么理由需要隐藏身体然后再次显示它?

任何反馈都将不胜感激,谢谢!

【问题讨论】:

    标签: javascript css reactjs sass gatsby


    【解决方案1】:

    此组件似乎试图避免在页面加载时出现未设置样式的内容。 Gatsby v2+ 肯定没有任何东西需要使用这种模式。您的所有 React 组件都在服务器端呈现,并在客户端重新水化。

    我强烈建议不要使用这种类型的模式。如果 JavaScript 不执行,则什么都看不到。如果客户端速度很慢并且 React 需要一段时间来为客户端补充水分,那么 componentDidMount 调用的延迟将远远超过超时中包含的 50 毫秒。在随后访问页面时,即使所有资产都可能已缓存,组件也会重新挂载,从而导致不必要的延迟。以此类推。

    【讨论】:

    • 感谢您的反馈。我认为没有必要设置可见性:在这种情况下也隐藏。但我不确定编写此代码的人的意图。
    猜你喜欢
    • 2021-08-23
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2021-07-22
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多