Stateless functional component 和 shouldComponentUpdate

来源:互联网 发布:淘宝店铺严重违规12分 编辑:程序博客网 时间:2024/05/17 02:27

之前看facebook官方说,对于stateless component 推荐使用 functional component, 因为速度会更快。今天看了几篇文章,才知道,实际上,facebook只是在文档上说未来他们将会优化functional component 的速度。实际使用时,有时使用pure component render + shouldComponentUpdate 会更快。

对于一个内容不经常变化,且props比较简单的无状态组件,使用pure render加上shouldComponentUpdate 会比函数式组件(functional component)更快。

对于内容经常变化,或者传入的props太复杂(比较是否变化太费时)时,不如直接render.

Stateless functional components and shouldComponentUpdate

For complex components, defining shouldComponentUpdate (eg. pure render) will generally exceed the performance benefits of stateless components.


It is worth keeping in mind that sometimes people abuse/overuse pure-render; it can sometimes be as or more expensive than running the render again, because you’re iterating over the array of props and potentially doing things like string compares, which is just extra work for components that ultimately return true and then proceed to rerender anyway. PureRender / shouldComponentUpdate really is considered an escape hatch for performance and is not necessarily something that should be blindly applied to every component.

如何优化render:
Component Rendering Performance in React

  • Skip render if possible
  • Cache expensive computations in variables outside render functions
  • … or separate logic into multiple components and manage rendering selectively
  • If possible, return early
  • Keep render() slim (think functional programming)
  • Keep comparisons shallow

又查了下React官方文档:

React.PureComponent

React.PureComponent is exactly like React.Component but implements shouldComponentUpdate() with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

Note
React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data.
Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

好吧,其实对于性能速度要求不是很高时(比如我其实是为了用React写我的portfolio),使用functional component 更简洁明了。

原创粉丝点击