LifeCycleCom.jsx
import React, { Component } from 'react'
// 定义一个子组件
class SubCom extends Component {
state = {
msg: '这是初始数据'
}
// 该生命周期函数可以监听页面数据的变化
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
// 当父组件数据发生变化才会触发该生命周期函数的执行
console.log('子-01-componentWillReceiveProps', nextProps, nextContext)
// 可能在某些场景下 视图没有更新,此时 需要 this.setState
}
// 该声明周期函数必须要有返回值,而且返回一个布尔值,true表示数据更新视图也更新,如果是false,就会阻止视图更新
shouldComponentUpdate(nextProps, nextState, nextContext) {
/*
nextProps: 更新后的数据
nextState: 初始数据
*/
console.log('子-02-shouldComponentUpdate', nextProps, nextState, nextContext)
return true
}
UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) {
console.log('子-03-componentDidUpdate', nextProps, nextState, nextContext)
}
render() {
console.log('子-04-render')
const { list } = this.props
return (
<div className="sub-com">
<h1>子组件</h1>
<ul>
{
list.map((item, index) => {
return <li key={index}>{item}</li>
})
}
</ul>
</div>
)
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('子-05-componentDidUpdate', prevProps, prevState, snapshot)
}
componentWillUnmount() {
console.log('子-06-componentWillUnmount')
}
}
export default class LifeCycleCom extends Component {
constructor(props) {
super(props)
this.state = {
msg: '演示旧版本生命周期函数:',
arr: ['vue', 'react', 'flutter']
}
console.log('父-01-contructor')
}
// 在这个阶段是可以请求数据,但是首页可能会出现白屏的现象,也有可能造成多次渲染等不确定的问题,而且在17.x版本中将要废弃该生命周期函数,所以不建议在componentWillMount这个阶段请求数据,可以在构造函数中请求数据
UNSAFE_componentWillMount() {
console.log('父-02-componentWillMount')
}
handleClick = (e) => {
const { arr } = this.state
arr.push(Math.random())
this.setState({arr})
}
render() {
console.log('父-03-render')
const { msg, arr } = this.state
return (
<div>
{
msg && <h1>{msg}</h1>
}
<button onClick={this.handleClick}>改变状态</button>
<SubCom list={arr} />
</div>
)
}
// 在这个阶段相当于window.onload,我们可以操作真实dom,
// 在此阶段请求接口
componentDidMount() {
console.log('父-04-componentDidMount')
}
}