因为react是单向数据流,数据主要是通过props从父节点传到子节点。如果顶层(父节点)的某个props改变了,react会重新渲染所有子节点。
当父组件的数据改变渲染的时候影响到子组件没有问题,但是如果父组件的数据改变不影响子组件和子组件无关,这时候可以在子组件里做判断屏蔽不受父组件影响。
可以在shouldComponentUpdate函数中进行判断,如果这个属性没有发生改变,那么父组件的渲染不去影响子组件。
shouldComponentUpdate(nextProps, nextState) {
if(nextProps.text==this.props.text){
return false;
}
return true;
}
当然这个this.props.text也可以改为this.state.text,(在componentWillReceiveProps中把props.text赋值给state.text)。具体解释看下文。
react的生命周期分为:
初始阶段:constructor
挂载阶段:componentWillMount,render,componentDidMount
更新阶段:componetWillReceiveProps,shouldComponentUpdate,componenetWillUpdate,render,componentUpdate
卸载阶段:componetWillUnMount
componentWillReceiveProps(newProps)是在组件更新过程中,监听props的变化。newProps是父组件传给当前组件的新props,但是这个props可能是没有变化的
。
shouldComponentUpdate返回一个布尔值,如果是true时继续执行更新过程;返回false则停止当前更新,即不会进行后面的componenetWillUpdate,render,componentUpdate。
父组件和子组件的生命周期过程:
父组件construtor,父组件componetWillMount,父组件render
子组件construtor,子组件componentWillMount,子组件render,子组件componentDidMount
父组件componentDidMount
组件更新时
父组件shouldComponentUpdate,父组件componentWillUpdate,父组件render
子组件componentWillReceiveProps,子组件shouldComponentUpdate,子组件componentWillUpdate,子组件render,子组件componentDidUpdate
父组件componentDidUpdate
这里需要注意,如果子组件是自己更新而不是被父组件触发更新,那么会少componentWillReceiveProps过程
主动更新和被动更新:主动少了一个componentWillReceiveProps
卸载
我们在边写组件边看界面效果的时候,页面会自动更新。那时候的生命周期过程是:
如果是父组件发生改变,父子组件的挂载阶段中,在子组件componetDidMount之前,会先父组件componentWillUnmount,再子组件componentWillUnmount,最后再子组件componentDidMount,父组件componentDidMount。
如果是子组件发生改变,挂载阶段中,在子组件componentDidMount之前,会先componentWillUnmount。
具体整个过程可以自己模拟一遍,写一个父组件和一个子组件,并写这些函数且打印日志,运行一遍之后就清楚了。