生命周期流程图:
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
//defaultProps->constructor->render
class Panel extends Component {
// class Panel extends React.PureComponent { // 他会比较两个状态相等就不会刷新视图 PureComponent是浅比较
static defaultProps = {
name: '浩浩'
}
constructor(props) {
super()
this.state = {
number: 0
}
localStorage.setItem('a', 1)
console.log('父组件1:constructor构造函数')
}
handleChange = () => {
console.log('----------------------------触发按钮的点击事件-------------------------')
let val = this.state.number
this.setState({
//即使把它变成0;每次都一样;也会触发componentWillUpdate+componentDidUpdate
number: val + 1
})
}
// 取本地的数据,同步的方式:采用渲染之前获取数据,只渲染一次
componentWillMount() {
localStorage.getItem('a')
console.log('父组件2:componentWillMount组件将要加载')
}
//将要更新前的判断,返回true时才会触发更新componentWillUpdate(第一次这个不会触发,只有发生事件时才会触发),参数分别代表的是下一次的属性,下一次的状态;在这里可以进行优化性能,
react中的PureComponent组件可以帮助进行性能优化
shouldComponentUpdate = (nextProps, nextState) => {
console.log('父组件shouldComponentUpdate,将要更新前的判断1')
console.log(nextProps)
console.log(nextState)
// return true怎么都会刷新
// return false怎么都不会刷新
return nextState.number % 2; //如果此函数种返回了false 就不会调用render方法了
//不要随便调用setstate,可能会死循环
// return true
}
componentWillUpdate = () => {
console.log('父组件componentWillUpdate,将要更新2')
}
componentDidUpdate = () => {
console.log('父组件componentDidUpdate,更新完毕3')
}
render() {
console.log('父组件3:父组件的render,渲染元素')
return (
<div>
<p>{this.state.number}</p>
<button onClick={this.handleChange}>改变状态</button>
<ChildCounter n={this.state.number}></ChildCounter>
</div>
)
}
componentDidMount() {
localStorage.getItem('a')
console.log('父组件4:componentDidMount组件挂载完成')
console.log(document)
}
}
class ChildCounter extends Component {
constructor(props) {
super()
console.log(' 子组件(1):constructor构造函数')
}
componentWillMount() {
console.log(' 子组件(2):子组件componentWillMount组件将要加载')
}
render() {
console.log(' 子组件(3):子组件的render渲染')
return (
<div>
{this.props.n}
</div>
)
}
componentDidMount() {
console.log(' 子组件(4):子组件componentDidMount组件挂载完成')
}
shouldComponentUpdate = (nextProps, nextState) => {
console.log(' 子组件shouldComponentUpdate,将要更新前的判断1')
console.log(nextProps)
console.log(nextState)
// return true怎么都会刷新
// return false怎么都不会刷新
return true; //如果此函数种返回了false 就不会调用render方法了
//不要随便调用setstate,可能会死循环
// return true
}
componentWillUpdate = () => {
console.log(' 子组件componentWillUpdate,将要更新2')
}
componentDidUpdate = () => {
console.log(' 子组件componentDidUpdate,更新完毕3')
}
//第一次不会执行;之后属性更新时,才会执行
componentWillReceiveProps=(newProps)=>{
console.log(' 子组件componentWillReceiveProps,属性更新')
console.log(newProps)
}
}
ReactDOM.render(<Panel name={'计数器'}></Panel>, document.getElementById('root'))