React生命周期
React的生命周期从广义上分为挂载、渲染、卸载三个阶段,在React的整个生命周期中提供很多钩子函数在生命周期的不同时刻调用。 描述的是使用class类组件提供的生命周期函数,每个组件都包含自己的生命周期方法,通过重写这些方法,可以在运行过程中特定的阶段执行这些方法
挂载过程
当组件实例被创建并插入DOM中时,其生命周期调用顺序如下:
- constructor()
- render()
- componentDidMount()
在这个阶段的componentWillMount()生命周期即将过时,在新代码中应该避免使用。
更新过程
当组件的props或state发生变化时会触发更新,组件更新的生命周期调用顺序如下:
- render()
- componentDidUpdate()
卸载
当组件从 DOM 中移除时会调用如下方法:
- componentWillUnmount()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React生命周期</title>
</head>
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
class Clock extends React.Component {
/*
* 组件初始化时只调用,
* 以后组件更新不调用,
* 整个生命周期只调用一次,此时可以修改state
*/
constructor(props) {
super(props);
this.state = { date: new Date() };
}
/*
* 这个就是组件初始化创建的时候才会执行的方法
* 并且只会执行一次,此时可以去修改 State里面的值
*/
componentDidMount() {
console.log("ComponentDidMount", this);
console.log(this.props);
console.log(this.state);
console.log("");
this.timer = setInterval(() => this.tick(), 1000);
}
/*
* 组件将要卸载时调用,
* 一些事件监听和定时器需要在此时清除
*/
componentWillUnmount() {
console.log("ComponentWillUnmount", this);
console.log(this.props);
console.log(this.state);
console.log("");
clearInterval(this.timer);
}
/*
你执行的方法函数可以写在这里,也可以写在底部
定时器
*/
tick() {
this.setState({ date: new Date() });
}
/*
* react最重要的步骤,
* 创建虚拟dom,
* 进行diff算法,当你组件传递数据更新变化都会执行 render
* 更新dom树都在此进行。此时就不能更改state了
*/
render() {
return (
<div>
<h1>{this.props.tips}</h1>
<h2>Now: {this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {
showClock: true,
tips: "Hello World!"
}
}
/*
会在更新后会被立即调用,首次渲染不会执行此方法。
当组件更新后,可以在此处对DOM进行操作,如果你对更新前后的props进行了比较,
也可以选择在此处进行网络请求(例如,当props未发生变化时,则不会执行网络请求。
*/
componentDidUpdate(prevProps, prevState) {
console.log("ComponentDidUpdate", this);
console.log(this.props);
console.log(this.state);
console.log("");
}
updateTips() {
this.setState((state, props) => ({
tips: "React update"
}));
}
changeDisplayClock() {
this.setState((state, props) => ({
showClock: !this.state.showClock
}));
}
render() {
return (
<div>
{this.state.showClock && <Clock tips={this.state.tips} />}
<button onClick={() => this.updateTips()}>更新tips</button>
<button onClick={() => this.changeDisplayClock()}>改变显隐</button>
</div>
);
}
}
var vm = ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
</html>