【问题标题】:Render loading screen while waiting for DOM to render after update在等待 DOM 更新后渲染时渲染加载屏幕
【发布时间】:2020-11-23 16:20:03
【问题描述】:

我想在我的 React 应用程序的 render() 函数运行时呈现加载屏幕。 This question 解决了应用程序初始加载的问题,但是我需要对应用程序状态进行更新,然后根据新状态重新渲染应用程序,这似乎非常昂贵。但是,我尝试的任何操作都会导致应用程序在渲染运行时完全冻结。有没有办法在等待 DOM 重新渲染时渲染动态加载屏幕?

这是一个显示我意图的代码框:https://codesandbox.io/s/elated-lamarr-fhqwe?file=/src/App.js

在示例中,我希望在渲染其他 div 时显示“加载”div(理想情况下,这将是某种动态“加载器”组件),然后在渲染完成后消失。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您有 conditional-rendering 用于此目的

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

    如果计算成本很高,您可以使用 memoize-one 之类的库,它可以帮助您在输入值没有变化的情况下跳过密集计算

    【讨论】:

    • isLoading ? &lt;Loader /&gt; -- 应该是this.state.isLoading ? &lt;Loader /&gt;吗?
    • Ya.... 只是将其作为示例发布。无论如何都会更新。谢谢指出:)
    • 好吧,问题不是计算慢,而是计算完成后的渲染。我将在问题中包含一个沙箱来澄清这一点。
    猜你喜欢
    • 2019-09-28
    • 2021-09-08
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多