1.constructor()
在这个周期中可以做的事情:
1. 初始化状态
2. 绑定this
3. 创建ref
2.getDerivedStateFromProps(props,state)
在这个周期中可以做的事情:
当父组件更新的时候,会传一些的新的属性进来,当有的属性我有用到的时候,这里返回的对象就会去跟状态 this.state={}里的对应属性合并
3.render()
注意:render()中不能使用setState()方法,不然会引起无限更新
this.setState({
show:false
})
4.componentDidMount()
在componentDidMount()周期可以做的事情:
1.注册事件;
2.发送请求
3.订阅 redux subscribe 订阅数据的方法
import React, { Component } from 'react';
// 挂载时
class App extends Component {
// state={}
constructor(props){
super(props)
console.log("1.执行了constructor")
// constructor()周期可以做的事情
//1.初始化状态
this.state={}
// 2.绑定this
this.handleClick=this.handleClick.bind(this)
//3.创建ref
this.ref=React.createRef()
}
handleClick(){}
static getDerivedStateFromProps(props,state){
console.log('2.执行力getDerivedStatefromprops')
// 作用:当父组件更新的时候,会传一些的新的属性进来,当有的属性我有用到的时候,这里返回的对象就会去跟状态 this.state={}里的对应属性合并
return {
show:true
}
}
render() {
console.log('3.执行了render()')
//注意:render()中不能使用setState()方法,不然会引起无限更新
// this.setState({
// show:false
// })
return (
<div>
<button id="btn">按钮被点击了</button>
</div>
);
}
componentDidMount(){
console.log("4.执行力componentDidMount")
// 在componentDidMount()周期可以做的事情
// 1.注册事件,定时器
document.getElementById('btn').addEventListener('click',function(){
console.log("按钮被点击了")
})
// 2.发送请求
// 3.订阅 redux subscribe 订阅数据的方法
}
}
export default App;