【问题标题】:React/Preact: how to temporarily avoid updating the DOM for a certain component?React/Preact:如何暂时避免更新某个组件的 DOM?
【发布时间】:2019-02-07 04:25:29
【问题描述】:

我正在使用带有 Webpack 代码分割的服务器端渲染。服务器返回组件的 HTML。但是,当 React 初始化时,由于我使用的是代码拆分,我想要渲染的 React 组件还没有下载。通常,我想显示一个加载屏幕。但是,组件的 HTML 已经呈现,所以我不想用加载屏幕替换它。

有没有办法让 React 暂时忽略组件而不更新 DOM?

组件看起来像这样:

export default class SomeRoute extends Preact.Component {
  constructor() {
    super();

    this.state = {
      Component: null,
    };
  }

  componentDidMount() {
    if (!this.state.component) {
      this.props.componentLoader().then(Component => this.setState({ Component }));
    }
  }

  render({}, { Component }) {
    if (!Component) {
      return (
        <p>Loading...</p>
      );
    }

    return (
      <Component />
    );
  }
}

&lt;Component /&gt; 的输出已经被服务器返回。

【问题讨论】:

    标签: javascript reactjs webpack preact


    【解决方案1】:

    您可以使用shouldComponentUpdate()。当你return false 时它不会更新组件。

    shouldCompnentUpdate(nextprops,nextstate){
        return Boolean(this.state.Component)
    }
    

    【讨论】:

    • 初始渲染不需要这样。此外,React 只使用了 render() 的先前输出
    • @Leojiang 你想阻止render() 即使组件被加载?你说组件和不更新 ;DOM
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2020-05-04
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多