import React, { Component } from 'react'
// 只有在类组件中才有生命周期
export default class App extends Component {
// 组件初始化 只执行一次
constructor(props) {
super(props);
console.log('constructor');
this.state = {
username: 'aaa'
}
}
// 执行N次
/* static getDerivedStateFromProps() {
console.log('getDerivedStateFromProps');
return {
username: 'abc'
}
} */
// 挂载完毕之前
/* UNSAFE_componentWillMount(){
console.log('UNSAFE_componentWillMount');
}
*/
// 组件挂载完毕 只执行1次 一般AJAX写在此处
componentDidMount() {
console.log('componentDidMount');
setTimeout(() => {
this.setState({
username: 'abc'
})
}, 3000);
}
// getDerivedStateFromProps 与 shouldComponentUpdate 只能有一个存在
// 是否让组件进行渲染 true渲染 false不渲染 组件渲染优化
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps,nextState); // immutable
if(nextState.username === this.state.username){
return false;
}
return true;
}
render() {
console.log('render');
return (
<div>
</div>
)
}
}