当我发现自己在react
component
中多次使用相同的component
(例如在组件上的不同方法中)时,最终会多次破坏props
。
这做法不好吗?我是否应该将正在多次解构的prop
分配给实例本身(类似于constructor()
中的this.propOfInterest = this.props.propOfInterest
)?
class MyComponent extends React.Component {
myMethod() {
const {
propOfInterest,
} = this.props
// do something with propOfInterest
}
render() {
const {
propOfInterest,
} = this.props
return (
<div className={propOfInterest}>
</div>
)
}
}
发布于 2018-11-08 00:26:35
解构并不是一个糟糕的实践,它不会以任何方式降低性能。在引擎盖下,无论您是否变形,Babel将在捆绑之前将您的代码转换成相同的语句。
所以基本上,
const { propOfInterest } = this.props;
和
const propOfInterest = this.props.propOfInterest;
将以同样的方式捆绑在一起。
如果将这两行复制到在线Babel传送器中,您将得到以下结果。
const { propOfInterest } = props;
const propInterest = props.propInterest;
会导致
var _props = props,
propOfInterest = _props.propOfInterest;
var propInterest = props.propInterest;
谈到性能,当您使用this
时,它就变成了一个实例变量。Nicholas 在他的书“高性能JavaScript”中说,理想情况下,实例变量的性能要慢一些。
当涉及Javascript数据时,访问它的方法有四种:文字值、变量、对象属性和数组项。在考虑优化时,文字值和变量的表现大致相同,并且比对象属性和数组项要快得多。 因此,每当您多次引用对象属性或数组项时,都可以通过定义变量获得性能提升。(这既适用于读写数据,也适用于写入数据。)
从作者的观点得出结论,破坏比将值存储在实例变量中要快得多。
如果我们能够创建一个杰斯普夫示例,我们就可以确定。
https://stackoverflow.com/questions/53199571
复制相似问题