在本章中,我们来了解组件生命周期方法。
生命周期方法
- componentWillMount - 在渲染之前在服务器端和客户端执行。
- componentDidMount - 仅在客户端的第一次渲染之后执行。 这是AJAX请求和DOM或状态更新应该发生的地方。此方法也用于与其他JavaScript框架以及任何延迟执行的函数(如
setTimeout
或setInterval
)进行集成,在这里使用它来更新状态,以便我们可以触发其他生命周期方法。 - componentWillReceiveProps - 只要在另一个渲染被调用之前更新
props
就被调用。 当我们更新状态时,从setNewNumber
触发它。 - shouldComponentUpdate - 应该返回
true
或false
值。 这将决定组件是否将被更新。 默认设置为true
。 如果确定组件在state
或props
更新后不需要渲染,则可以返回false
值。 - componentWillUpdate - 在渲染之前被调用。
- componentDidUpdate - 在渲染之后被调用。
- componentWillUnmount - 在从dom卸载组件后被调用,也就是卸载
main.js
中的组件。
在下面的例子中,将在构造函数中设置初始状态。 setNewnumber
用于更新状态。 所有生命周期方法都在内容组件中。
文件:App.jsx -
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;
文件:main.js -
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);
初始渲染之后,应该会得到如下演示效果 -
只有componentWillMount
和componentDidMount
将被记录在控制台中,因为还没有更新任何东西。
当点击INCREMENT按钮时,将发生更新,并触发其他生命周期方法。
十秒钟后,组件将被卸载,最后一个事件将被记录在控制台中。
注 - 生命周期方法将始终以相同的顺序调用,因此按照示例中所示的正确顺序编写生命周期方法是一种很好的做法。
上一篇:
ReactJS组件API
下一篇:
ReactJS表单