我知道无状态组件使用起来要舒服得多(在特定情况下),但由于你不能使用shouldComponentUpdate,这是否意味着组件将为每个props更改重新渲染?我的问题是,使用具有智能的shouldComponentUpdate的类组件比使用无状态组件更好(性能方面) .
就性能而言,无状态组件是否是更好的解决方案?考虑这个愚蠢的例子:
const Hello =(props) =>(
<div>
<div> {props.hello}</div>
<div>{props.bye}</div>
</div>);
VS
class Hello extends Component{
shouldComponentUpdate(nextProps){
return nextProps.hello !== this.props.hello
};
render() {
const {hello, bye} = this.props;
return (
<div>
<div> {hello}</div>
<div>{bye}</div>
</div>
);
}
}
让我们假设这些组件都有2个道具,只有其中一个我们想要跟踪和更新(如果是常见的用例),使用无状态功能组件或类组件会更好吗?
UPDATE
在做了一些研究之后我同意明确的答案 . 尽管类组件(使用shouldComponentUpdate)的性能更好,但似乎简单组件的改进可以忽略不计 . 所以我的看法是这样的:
-
对于复杂组件,使用由PureComponent或Component扩展的类(取决于您是否要实现自己的shouldComponentUpdate)
-
对于简单组件使用功能组件,即使它意味着重新运行
-
尝试从最接近的类基本组件中减少更新量,以使树尽可能静态(如果需要)
1 回答
我想你应该读Stateless functional components and shouldComponentUpdate #5677
https://github.com/facebook/react/issues/5677#issuecomment-165125151
https://github.com/facebook/react/issues/5677#issuecomment-241190513
我还建议检查https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f
回答这个问题:这取决于 . 如果你有复杂/重型组件,你可能应该实现
shouldComponentUpdate
. 否则使用常规功能应该没问题 . 我不认为为像你这样的组件实现shouldComponentUpdate
会产生很大的不同,它可能不值得花时间实现 . 您还应该考虑从PureComponent
而不是Component
进行扩展 .