gpt4 book ai didi

javascript - react : Impact of conditional rendering on performance

转载 作者:行者123 更新时间:2023-12-05 06:47:37 28 4
gpt4 key购买 nike

在组件树中向下或向上有条件地渲染弹出窗口(例如通过 {shouldShowLoading && <LoadingSpinner />} 加载微调器弹出窗口)是否更有意义?那么以下两个选项中哪一个是有利的 - 或者在性能上没有差异?

  1. 在组件层次结构中更靠下(例如,位于靠近触发弹出窗口的按钮的左侧)? - 例如在下面的箭头位置

                             App.tsx
    / \
    Header.tsx Counter.tsx
    / \
    --> HeaderElement.tsx HeaderElement.tsx
    /
    Badge.tsx

    使用这样的伪代码:

    const HeaderElement = () => {
    // ... shouldShowLoading is defined here
    return (
    <div>
    <Title />
    {shouldShowLoading && <LoadingSpinner />}
    </div>
    );
    }

或者相反

  1. ...进一步向上(例如在主导航旁边的根目录中)? - 例如在下面的箭头位置

    -->                      App.tsx
    / \
    Header.tsx Counter.tsx
    / \
    HeaderElement.tsx HeaderElement.tsx
    /
    Badge.tsx

    使用这样的伪代码:

    const App = () => {
    // ... shouldShowLoading is defined here or in global state
    return (
    <div>
    < RootNavigation />
    {shouldShowLoading && <LoadingSpinner />}
    </div>
    );
    }

到目前为止我的想法和调查:

React 的协调算法 总是创建 DOM 的第二个虚拟树(计算成本低),但最终只渲染与现有虚拟 DOM 树相比实际发生变化的子树,因为重新渲染的计算成本很高.

App.tsx 中的条件渲染也是如此(如上所示)导致其下方的所有内容(即整个应用程序)重新呈现? - 我相信情况并非如此,但在阅读了更多关于 React 的协调算法 之后 in the React docs我还是说不出为什么..

问题:

谁能给我解释一下为什么在条件渲染的情况下不是所有的子组件都必须重新渲染?协调算法使用哪种特殊启发式算法?还是我错了?

最佳答案

App.tsx是否选择有条件地渲染其后代并不等同于子树是否发生了变化。

children 可能没有导致他们改变的依赖关系。

关于javascript - react : Impact of conditional rendering on performance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036837/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com