本文共 2766 字,大约阅读时间需要 9 分钟。
组件的生命周期可分成三个状态:
组件的生命周期状态:说明在不同时机访问组件,组件正处在生命周期的不同状态上。在不同的生命周期状态访问,就产生不同的方法。
生命周期的方法如下:
import React from 'react'import ReactDom from 'react-dom'class Root extends React.Component{ constructor(props){ super(props) this.state = {flag: true, count: 0} console.log('Root constructor~~~') } componentWillMount(...args){ console.log('will mount', args) } componentDidMount(...args){ console.log('did mount', args) } componentWillUnmount(...args){ console.log('will unmount', args) } // update componentWillReceiveProps(nextProps){ console.log(' will receive props', this.props, nextProps) } shouldComponentUpdate(nextProps, nextState){ // console.log('should update', this.props, nextProps) console.log('should update', this.state, nextState) // return nextProps.count > 3?true: false return (nextProps.count > 3 || nextState.count > 3)?true:false // 注意:nextPState看似return false拒绝,但是要知道只是没有render,state的值还是还是被更新了 } componentWillUpdate(nextProps, nextState){ // console.log('will update', this.props, nextProps) console.log('will update', this.state, nextState) } handleClick(e){ this.setState({count: this.state.count + 1}) } render(){ console.log('Root render~~~~~~') return金州勇士} componentDidUpdate(preProps, preState){ // console.log('did update', this.props, preProps) console.log('did update', this.state, preState) }}class App extends React.Component{ constructor(props){ super(props) this.state = {count: 0} } handleClick(e){ this.setState({count: this.state.count + 1}) } render(){ return}}ReactDom.render(count = {this.state.count} , document.getElementById('root'))
由图可知:constructor构造器是最早执行的函数。组件构建好之后,如果更新组件的state或props(注意在组件内props是只读的),就会render渲染前触发一系列的更新生命周期函数。
转载地址:http://ovfvi.baihongyu.com/