React生命周期
React生命周期
componentWillMount组件将要被挂载,这个阶段发生在组件 componentDidMount组件已经挂载完成,这个阶段发生在 componentWillReceiveProps组件将要接收新的属性,这个阶段发生在组件的属性改变的时候,并且是组件重新渲染的过程中第一个执行的方法 shouldComponentUpdate组件是否要更新,这个阶段发生在 componentWillUpdate组件将要更新,这个阶段发生在 componentWillUnmount组件将要被销毁,当组件由于功能需求或者用户操作,需要卸载的时候执行此钩子函数,一般用于解除组件的定时器或者事件监听函数 代码示例//定义一个时钟组件 class Clock extends Component { constructor(){ super(); this.state={ time: new Date().toLocaleString() }; } componentWillReceiveProps(){ console.log("clock receive props"); } shouldComponentUpdate(){ console.log("clock should update"); return true; } componentWillUpdate(){ console.log("clock will update"); } componentDidUpdate(){ console.log("clock did update"); } componentWillMount(){ console.log("clock will mount"); } componentDidMount(){ console.log("clock did mount"); this.timer=setTimeout(()=>{ this.setState({ time: new Date().toLocaleString() }); },1000); } componentWillUnmount(){ console.log("clock unmount"); clearInterval(this.timer); } render(){ console.log("clock render"); return ( <div> {this.props.country }: {this.state.time} </div> ) } } //在Index组件中使用Clock组件,并且将Index组件在页面中渲染出来 class Index extends Component { constructor(){ super(); this.state={ isShow: true,country: "china" }; } shouldComponentUpdate(){ console.log("index should update"); return true; } componentWillUpdate(){ console.log("index will update"); } componentDidUpdate(){ console.log("index did update"); } componentWillMount(){ console.log("index will mount"); } componentDidMount(){ console.log("index did mount"); } render(){ console.log("index render"); return ( <div> { this.state.isShow? <Clock country={this.state.country} /> : null } <button onClick={()=>{this.setState({isShow: !this.state.isShow})}}> { this.state.isShow?"hide":"show" } </button> { this.state.isShow? <button onClick={()=>{this.setState({country: this.state.country==="china"?"usa":"china"})}}>transform</button> : null } </div> ) } } 页面首次被渲染的时候依次在控制台打印出如下结果:
紧接着,一秒过后,定时器中的函数执行,对Clock组件的状态进行了修改,于是浏览器依次输出如下结果:
从上面可以看出update类型的钩子函数只会在组件存在之后状态改变时执行。之后点击transform按钮,将Clock接收的props中的country属性改变成usa,浏览器输出如下结果:
再点击hide按钮,使Clock组件从页面中卸载,浏览器输出如下结果:
以上就是react组件完整的生命周期,每个react组件从创建到销毁都会经历如此过程,这些生命周期钩子能够帮助我们实现项目中各种各样的功能需求。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |