实例一
class Life extends React.Component{
constructor(props){
super(props);
console.log("constructor()");
};
componentWillMount(){
console.log("componentWillMount()")
};
render(){
console.log("render()");
return (
<div>
<h1>组件生命周期</h1>
</div>
)
}
componentDidMount(){
console.log("componentDidMount()")
};
shouldComponentUpdate(){
console.log("shouldComponentUpdate()")
}
componentWillUpdate(){
console.log("componentWillUpdate()")
}
componentDidUpdate(){
console.log("componentDidUpdate()");
}
componentWillUnmount(){
console.log("componentWillUnmount()")
}
}
ReactDOM.render(
<Life />,
document.getElementById("root")
);
实例二
class Life extends React.Component{
constructor(props){
super(props);
console.log("constructor()");
this.state = {
age : 1
}
};
UNSAFE_componentWillMount(){
console.log("componentWillMount()")
};
render(){
console.log("render()");
return (
<div>
<h1>我是树妖,今年{this.state.age}了</h1>
<button onClick={()=>ReactDOM.unmountComponentAtNode(root)}>砍树</button>
</div>
)
}
componentDidMount(){
console.log("定时器正在默默工作!");
this.interValId = setInterval(()=>{
this.setState({
age : this.state.age + 1
});
},2000);
};
UNSAFE_componentWillUpdate(){
console.log("componentWillUpdate()-------------")
}
componentDidUpdate(){
console.log("componentDidUpdate()");
}
componentWillUnmount(){
console.log("componentWillUnmount()");
clearInterval(this.interValId)
}
}
ReactDOM.render(
<Life />,
document.getElementById("root")
);