简体   繁体   English

React / Preact:如何暂时避免为某个组件更新DOM?

[英]React/Preact: how to temporarily avoid updating the DOM for a certain component?

I'm using server-side rendering with Webpack's code-splitting. 我在Webpack的代码拆分中使用服务器端渲染。 The server returns the HTML for the component. 服务器返回组件的HTML。 However, when React initializes, since I'm using code-splitting, the React component I want to render isn't downloaded yet. 但是,在React初始化时,由于我正在使用代码拆分功能,因此我要渲染的React组件尚未下载。 Typically, I'd want to display a loading screen. 通常,我想显示一个加载屏幕。 However, the HTML for the component is already rendered, so I don't want to replace it with a loading screen. 但是,该组件的HTML已经呈现,因此我不想将其替换为加载屏幕。

Is there a way to get React to temporarily ignore the component and not update the DOM? 有没有办法让React暂时忽略该组件而不更新DOM?

The component looks something like this: 该组件看起来像这样:

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 />
    );
  }
}

The output of <Component /> is already returned by the server. 服务器已返回<Component />的输出。

You can use shouldComponentUpdate() . 您可以使用shouldComponentUpdate() When you return false it will not update the component. 当您return false ,它将不会更新组件。

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

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

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