简体   繁体   中英

Render loading screen while waiting for DOM to render after update

I want to render a loading screen while the render() function of my React app is running. This question solves the problem for the initial loading of the application, however I need to perform updates to the app state and re-render the application afterward based on the new state, which appears to be very costly. However, anything I try causes the app to freeze entirely while the render is running. Is there a way to render a dynamic loading screen while waiting for the DOM to re-render?

Here is a codesandbox showing my intentions: https://codesandbox.io/s/elated-lamarr-fhqwe?file=/src/App.js

In the example, I would like for the "LOADING" div to show (ideally this would be some sort of dynamic "loader" component) while the other divs are being rendered, and then disappear when the render is done.

You have conditional-rendering for this purpose

...

this.state = {
  isLoading: true
};

...
componentDidMount() {
  expensiveCalculation(...);
  this.setState({ isLoading: false }); // Add additional state updates as per above results
}

...
render() {
  this.state.isLoading ? <Loader /> : <Component {...props} />;
}

If the computation is expensive, you can use the libraries like memoize-one which helps you to skip the intensive calculations if there is no change in input values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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