我们都知道Render在组件实例化和存在期时都会被执行。实例化在componentWillMount执行完成后就会被执行,这个没什么好说的。在这里我们主要分析存在期组件更新时的执行。
存在期的方法包含:
这些方法会在组件的状态或者属性发生发生变化时被执行,如果我们使用了Redux,那么就只有当属性发生变化时被执行。下面我们将从几个场景来分析属性的变化。
首先我们创建了HelloWorldComponent,代码如下所示:
import * as React from "react"; class HelloWorldComponent extends React.Component { constructor(props) { super(props); } componentWillReceiveProps(nextProps) { console.log('hello world componentWillReceiveProps'); } render() { console.log('hello world render'); const { onClick, text } = this.props; return ( ); } } HelloWorldComponent.propTypes = { onClick: React.PropTypes.func, }; export default HelloWorldComponent;
AppComponent组件的代码如下:
class MyApp extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } onClick() { console.log('button click'); this.props.addNumber(); } render() { return () } } const mapStateToProps = (state) => { return { count: state.count } }; const mapDispatchToProps = { addNumber }; export default connect(mapStateToProps, mapDispatchToProps)(MyApp);
这里我们使用了Redux,但是代码就不贴出来了,其中addNumber方法会每次点击时将count加1。
这个时候当我们点击button时,你觉得子组HelloWorldComponent的render方法会被执行吗?
如图所示,当我们点击button时,子组件的render方法被执行了。可是从代码来看,组件绑定的onClick和text都没有发生改变啊,为何组件会更新呢?
如果在子组件的componentWillReceiveProps添加这个log:console.log(‘isEqual', nextProps === this.props); 输出会是true还是false呢?
是的,你没有看错,输出的是false。这也是为什么子组件会更新了,因为属性值发生了变化,并不是说我们绑定在组件上的属性值。每次点击button时会触发state发生变化,进而整个组件重新render了,但这并不是我们想要的,因为这不必要的渲染会极其影响我们应用的性能。
在react中除了继承Component创建组件之外,还有个PureComponent。通过该组件就可以避免这种情况。下面我们对代码做点修改再来看效果。修改如下:
class HelloWorldComponent extends React.PureComponent
这次在点击button时发生了什么呢?
虽然componentWillReceiveProps依然会执行,但是这次组件没有重新render。
所以,我们对于无状态组件,我们应该尽量使用PureComponent,需要注意的是PureComponent只关注属性值,也就意味着对象和数组发生了变化是不会触发render的。
荒野乱斗国际版 (BrawlStars)最新版本v56.274
下载一波超人内置修改器菜单版 安卓版v1.0.2
下载敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载继承了一座戏园子无限声望铜钱版 内置菜单最新版v1.7
继承了一座戏园子折相思版是游戏的破解版本,在该版本中为玩家提
山河半世橙光清软金手指版 无限鲜花v3.24
山河半世是一款超级好玩的橙光恋爱游戏,在游戏中玩家们需要扮演
蓬莱手游折相思版 安卓版v1.0.0
蓬莱免广告版是游戏的修改版本,在该版本中为玩家去除了广告,玩
当红影后橙光游戏破解版2025 最新版v1.0
当红影后橙光破解版是一款超级好玩的娱乐圈题材的橙光游戏,在这
忽然成了万人迷清软完结版 无限鲜花版v12.15
忽然成了万人迷破解版是一款非常好玩的男性向橙光游戏,在有一天