1. 组件的生命周期
组件的生命周期可分成三个状态:
- Mounting:已插入真是DOM
- Updating: 真该被重新渲染
- Unmounting:已移出真实DOM
组件的生命周期状态:说明在不同时机访问组件,组件正处在生命周期的不同状态上。在不同的生命周期状态访问,就产生不同的方法。
生命周期的方法如下:
- 装载组件触发:componentWillMount在渲染前调用,在客户端也在服务端,只会在装载之前调用一次;componentDidMount在第一此渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDomNode来进行访问。如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout,setInterval或者发送AJAX请求等操作(阻止异步操作阻塞UI)。只在装载完成后调用一次,在render之后。
- 更新组件触发——这些方法不会在首次render组件的周期调用。componentWillReceiveProps(nextProps)在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。shouldComponentUpdate(nextProps, nextState)返回一个布尔值,在组件接收到新的prpos或者state时被调用。在初始化时或者使用forceUpdate时不被调用。可以在你确认不需要更新组件时使用;如果设置为false,就是不允许更新组件,那么componenWillUpdate、componentDidUpdate不会执行。componentWillUpdate(nextProps, nextState)在组件接收新的props或者state但还没有render时被调用,在初始化时不会被调用。componentDidUpdate(preProps, preState) 在组件完成更新后立即调用,在初始化时不会被调用。
- 卸载组件触发:componentWillUnmount在组件从DOM中移除的时候立即被调用。
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 <div onClick={this.handleClick.bind(this)}>金州勇士</div>
}
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 <div onDoubleClick={this.handleClick.bind(this)}>
<Root count={this.state.count} />
count = {this.state.count}
</div>
}
}
ReactDom.render(
<App />,
document.getElementById('root')
)
由图可知:constructor构造器是最早执行的函数。组件构建好之后,如果更新组件的state或props(注意在组件内props是只读的),就会render渲染前触发一系列的更新生命周期函数。