gpt4 book ai didi

javascript - 为什么无状态组件吃内存

转载 作者:行者123 更新时间:2023-11-29 16:52:22 24 4
gpt4 key购买 nike

向任何喜欢 React 的人提个简单的问题

我做了一个 jsbin example我正在尝试观察 React 是否对无状态组件进行任何内存优化

如果你对那个窗口进行堆转储,你应该能够看到 BsDiv 实例。这是否意味着我使用的所有组件都将保留在运行时?

enter image description here

(我自己没有对该对象的任何引用)

我很担心这一点,因为 React 组件由其他组件组成,依此类推 - 这意味着任何 Panel、Alert 和我愿意使用的任何东西都可能很容易有 5 个实例。

是否期望它以这种方式运行?

最佳答案

首先:请注意 React 对无状态功能组件有特殊的语法。您的示例代码使用该语法,因此 React 不知道您的组件是无状态的。

不是无状态功能组件:

class BsDiv extends React.Component{
render(){
return (<div className={this.props.cls}>{this.props.children}</div>)
}
}

这些无状态功能组件:

// component is just a function
const BsDiv = props => <div className={props.cls}>{props.children}</div>

// Using object destructuring syntax
const BsDiv = ({cls, children}) => <div className={cls}>{children}</div>;

其次:React 尚未对无状态功能组件应用任何重大优化。

来自 their blog (强调我的):

This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

因此,通过编写无状态功能组件,您可以选择 React 为这个“更简单”的组件所做的 future 优化。

以下是有关 future 可能的优化的更多信息:

https://github.com/facebook/react/issues/5677#issuecomment-165125151

How will React 0.14's Stateless Components offer performance improvements without shouldComponentUpdate?

关于javascript - 为什么无状态组件吃内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022121/

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