React 組件的生命周期函數(shù),又叫鉤子函數(shù),它能響應(yīng)不同的狀態(tài)。
在本章節(jié)中我們將討論 React 組件的生命周期。
組件的生命周期可分成三個(gè)狀態(tài):
- Mounting:已插入真實(shí) DOM
- Updating:正在被重新渲染
- Unmounting:已移出真實(shí) DOM
生命周期的方法有:
-
componentWillMount 在渲染前調(diào)用,在客戶(hù)端也在服務(wù)端。
-
componentDidMount : 在第一次渲染后調(diào)用,只在客戶(hù)端。之后組件已經(jīng)生成了對(duì)應(yīng)的DOM結(jié)構(gòu),可以通過(guò)this.getDOMNode()來(lái)進(jìn)行訪問(wèn)。 如果你想和其他JavaScript框架一起使用,可以在這個(gè)方法中調(diào)用setTimeout, setInterval或者發(fā)送AJAX請(qǐng)求等操作(防止異部操作阻塞UI)。
-
componentWillReceiveProps 在組件接收到一個(gè)新的prop時(shí)被調(diào)用。這個(gè)方法在初始化render時(shí)不會(huì)被調(diào)用。
-
shouldComponentUpdate 返回一個(gè)布爾值。在組件接收到新的props或者state時(shí)被調(diào)用。在初始化時(shí)或者使用forceUpdate時(shí)不被調(diào)用。
可以在你確認(rèn)不需要更新組件時(shí)使用。 -
componentWillUpdate在組件接收到新的props或者state但還沒(méi)有render時(shí)被調(diào)用。在初始化時(shí)不會(huì)被調(diào)用。
-
componentDidUpdate 在組件完成更新后立即調(diào)用。在初始化時(shí)不會(huì)被調(diào)用。
-
componentWillUnmount在組件從 DOM 中移除的時(shí)候立刻被調(diào)用。
這些方法的詳細(xì)說(shuō)明,可以參考官方文檔。
以下實(shí)例在 Hello 組件加載以后,通過(guò) componentDidMount 方法設(shè)置一個(gè)定時(shí)器,每隔100毫秒重新設(shè)置組件的透明度,并重新渲染:
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {opacity: 1.0};
}
componentDidMount() {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
}
render () {
return (
<div style={{opacity: this.state.opacity}}>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<Hello name="world"/>,
document.body
);
以下實(shí)例初始化 state , setNewnumber 用于更新 state。所有生命周期在 Content 組件中。
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {data: 0};
this.setNewNumber = this.setNewNumber.bind(this);
}
setNewNumber() {
this.setState({data: this.state.data + 1})
}
render() {
return (
<div>
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data}></Content>
</div>
);
}
}
class Content extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECEIVE PROPS!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
}
ReactDOM.render(
<div>
<Button />
</div>,
document.getElementById('example')
);
更多建議: