gpt4 book ai didi

reactjs - 重复调用ReactDOM.render和内存泄漏

转载 作者:行者123 更新时间:2023-12-03 13:43:13 25 4
gpt4 key购买 nike

关于这个React page它表示您需要手动调用 unmountComponentAtNode 因为:

This is important and often forgotten. Forgetting to call unmountComponentAtNode will cause your app to leak memory.

我有一个应用程序不断地将属性传递给根组件并调用ReactDOM.render。我是否需要为容器元素调用 unmountComponentAtNode 以防止“内存泄漏”(无论这意味着什么)?

我尝试这样做,并注意到它会导致重新安装所有子组件,而在没有 unmountComponentAtNode 的情况下调用 ReactDOM.render 似乎会进行比较,并且不会再次安装任何子组件。

那么,在没有 unmountComponentAtNode 的情况下调用 ReactDOM.render 可以吗?这会导致内存泄漏吗?上 this page它在 ReactDOM.render 下说:

If the ReactElement was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component. ReactDOM.render() controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called. Later calls use React’s DOM diffing algorithm for efficient updates.

它没有提到任何副作用。

编辑:我使用 Chrome 完成了一些简单的任务,其中使用 1 个简单组件调用 ReactDOM.render 100 万次,使用/不使用 unmountComponentAtNode。根据 Chrome 任务管理器的说法,如果没有它,页面大约需要 5 秒才能完成,然后卡住并消耗了 10 倍(我停止了它,因为它卡住了我的窗口)。因此,当证据表明使用 unmountComponentAtNode 防止内存泄漏可能会导致内存泄漏时,不确定它们是什么意思。

最佳答案

ReactDOM.render 可用于使用新的 props 更新顶级组件。这是一个完全可以接受的用途。 unmountComponentAtNode 的作用是从 DOM 中删除组件的顶级 DOM 节点。否则,由于 React 对 DOM 节点的引用,DOM 节点将被保留,从而导致内存泄漏。

关于reactjs - 重复调用ReactDOM.render和内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35337349/

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