在本章中,我们来了解组件生命周期方法。
settimeout
或setinterval
)进行集成,在这里使用它来更新状态,以便我们可以触发其他生命周期方法。props
就被调用。 当我们更新状态时,从setnewnumber
触发它。true
或false
值。 这将决定组件是否将被更新。 默认设置为true
。 如果确定组件在state
或props
更新后不需要渲染,则可以返回false
值。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按钮时,将发生更新,并触发其他生命周期方法。
十秒钟后,组件将被卸载,最后一个事件将被记录在控制台中。
注 - 生命周期方法将始终以相同的顺序调用,因此按照示例中所示的正确顺序编写生命周期方法是一种很好的做法。