Mounting / 掛載階段
getDefaultProps->getInitialState->componentWillMount -> render ->componentDidMount
getDefaultProps 初始化props
- 在這里可以給組件預(yù)設(shè)默認(rèn)的Props值票彪,防止組件渲染報(bào)錯(cuò)
// 舊寫法
getDefaultProps() {
return {
style: {}
}
}
// ES6
static defaultProps = {
style: {}
}
getInitialState 初始化state
// 舊寫法
getInitialState() {
return { visible: false }
}
// ES6
constructor(props) {
super(props);
this.state = { visible: false }
}
// 或直接在組件第一層寫
class MyComponent extends React.Component {
constructor() {}
state = { visible: false }
// ...
}
componentWillMount 準(zhǔn)備掛載組件
- 在此處可以做一些組件準(zhǔn)備動(dòng)作
componentWillMout() {
// 第一次掛載時(shí)不可見,就不掛載屹电,避免默認(rèn)不可見時(shí)也fadeOut
if(this.state.visible) {
this.render = this.renderBody
}
}
renderBody() {
return (<div className={this.state.visible ? 'fadeOut' : 'fadeIn'>延遲加載的文字</div>)
}
render() {
return <div/>
}
render 渲染組件
render() {
// 注意此處需要保證有且只有一個(gè)組件返回,如果實(shí)在不想渲染一個(gè)元素,可以返回<noscript>
return <div/>
}
componentDidMount 組件掛載完畢
- 可以在此處執(zhí)行與服務(wù)端的交互
componentDidMount() {
// 只有不在掛載中或更新中狀態(tài)的生命鉤子才可以獲取到this.refs
console.log(this.layer);
}
render() {
return <div ref={c=> this.layer = c}>哈哈</div>
}
Updating / 更新階段
componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
componentWillReceiveProps 組件將接收并更新Props
- 這個(gè)鉤子可以在組件props發(fā)生變動(dòng)時(shí)幫助我們執(zhí)行一些相應(yīng)操作专甩,在這個(gè)鉤子中可以執(zhí)行setState更新狀態(tài)
componentWillReceiveProps (nextProps) {
if(this.props.index !== nextProps.index) {
// 當(dāng)外部傳入的index發(fā)生變化時(shí),組件執(zhí)行一些操作...
}
}
shouldComponentUpdate 組件是否應(yīng)該更新
- 當(dāng)整個(gè)應(yīng)用update頻繁時(shí)奸鬓,可以通過這個(gè)鉤子對(duì)本組件的更新進(jìn)行控制,防止無用刷新谱仪,可提高性能
shouldComponentUpdate(nextProps, nextState) {
// 根據(jù)state數(shù)據(jù)的時(shí)間戳來決定是否應(yīng)該更新組件
return this.state.timeStamp !== nextState.timeStamp
}
componentWillUpdate 準(zhǔn)備更新組件
- 此處不應(yīng)該setState玻熙,可能造成過渡更新
componentWillUpdate(nextProps, nextState) {
if(this.props.childCount !== nextProps.childCount) {
// childCount發(fā)生了變化,對(duì)應(yīng)做出操作
}
}
render 渲染(更新)組件
- 與Mounting階段相似
componentDidUpdate 組件更新完畢
componentDidUpdate(prevProps, prevState) {
}
Unmounting / 卸載階段
componentWillUnmount
componentWillUnmount 準(zhǔn)備卸載組件
- 可以在此處對(duì)組件狀態(tài)芽卿、store數(shù)據(jù)揭芍、定時(shí)器等等進(jìn)行清除
componentDidMount() {
// 組件掛載完畢之后開始執(zhí)行定時(shí)器
this.timer = window.setInterval(()=> {
// 定時(shí)器執(zhí)行的一些操作
}, 300)
}
componentWillUnmount() {
// 組件卸載時(shí)清除定時(shí)器胳搞,防止內(nèi)存消耗
window.clearInterval(this.timer);
}