在本章中,我們將討論組件生命周期方法。
componentWillMount 在渲染之前在服務器和客戶端上均已執(zhí)行。
componentDidMount僅在客戶端執(zhí)行第一個渲染之后執(zhí)行。這是應該進行AJAX請求和DOM或狀態(tài)更新的地方。此方法還用于與其他JavaScript框架以及延遲執(zhí)行的任何函數(shù)(例如setTimeout或)集成setInterval。我們正在使用它來更新狀態(tài),以便我們可以觸發(fā)其他生命周期方法。
componentWillReceiveProps道具更新后立即調用,然后調用另一個渲染器。我們是從setNewNumber更新狀態(tài)時觸發(fā)的。
shouldComponentUpdate應該返回true或false值。這將確定組件是否將被更新。true默認情況下設置為。如果您確定組件不需要在更新后state或props更新后呈現(xiàn),則可以返回false值。
componentWillUpdate 在渲染之前被調用。
componentDidUpdate 在渲染后立即調用。
componentWillUnmount從dom卸下組件后調用。我們正在中卸載組件main.js。
在下面的示例中,我們將state在構造函數(shù)中設置初始值。將setNewnumber用于更新的state。所有生命周期方法都在Content組件內部。
import React from 'react';
class App 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 RECIEVE 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>
);
}
}
export default App;import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 10000);初始渲染后,我們將獲得以下屏幕。
