生命周期(旧)
1.初始化阶段:由ReactDOM.render()触发—初次渲染
(1). constructor
(2). componentWillMount()
(3). render()
(4). componentDidMount() =====>常用,初始化:开启定时器,发送网络请求,订阅消息
2.更新阶段:由组件内部this.setState()或父组件重新render触发
(1). shouldComponentUpdate
(2). componentWillUpdate()
(3). render() =====>必须
(4. componentDidUpdate
3.卸载组件:由ReactDOM.unmountComponentAtNode()触发
(1). componentWillUnmount() =====>常用,收尾:关闭定时器,取消订阅消息
引出生命周期(旧)
//创建组件
//生命周期回调函数 <=> 生命周期钩子函数 <=> 生命周期函数
class Life extends React.Component{
state = { opacity:1 }
death = ()=>{
//卸载组件
ReactDOM.unmountComponentAtNode(document.getEelementById('test'))
}
//组件挂载完毕
componentDidMount(){
this.timer = setInterval(()=>{
//获取原来的状态
let {opactiy} = this.state
opacity -= 0.1
if(opactiy<=0) opactiy=1
//设置新的透明度
this.setState({opactiy})
},200)
}
//组件将要卸载
componentWillUnmount(){
clearInterval(this.timer)
}
//render调用的时机:初始化渲染以及状态更新后
render(){
return(
<div>
<h2 style={{opacity:this.state.opactiy}}>React学不会怎么办</h2>
<button onClick = {this.death} >不活了</button>
</div>
)
}
}
//渲染组件
ReactDOM.rener(<Left/>,document.getElementById("test") )
生命周期(旧)
class Add extends React.Component{
constructor(props){
console.log("1.constructor")
super(props)
this.state = { count:0 }
}
state = { count:0 }
add = ()=>{
const {count} = this.state
this.setState({ count:count+1 })
}
death = ()=>{
ReactDOM.unmount(document.getElementById('test'))
}
//强制更新不改状态
force = ()=>{
this.forceUpdate()
}
//组件将要挂载的钩子
componentWillMount(){
console.log('2.componentWillMount');
}
//组件挂载完毕的钩子
componentDidMount(){
console.log('4.componentDidMount');
}
//组件将要卸载的钩子
componentWillUnmount(){
console.log('conponentWillUnmount');
}
//控制组件更新的"阀门"
shouldComponentUpdate(){
console.log('shouldComponentUpdate');
return true
}
//控制将要更新的钩子
componentWillUpdate(){
console.log('componentWillUpdate');
return true ;
}
//组件更新完毕的钩子
componentDidUpdate(){
console.log('componentDidUpdate');
}
render(){
console.log('3.render');
const { count } = this.state
return(
<div>
<h2>当前求和为</h2>
<button onClick="this.add">点我+1</button>
<button onClick="this.death">卸载组件</button>
<button onClick="this.force">不更改任何状态中的数据,强制更新一下</button>
</div>
)
}
}
ReactDOM.render(<Add/>,document.getElementById('test'))
//父子关系
class A extends React.Component{
state = {carName:'bmw'}
changeCar = ()=>{
this.setState({carName:'audi'})
}
render(){
return(
<div>
<div>A</div>
<button onClick={this.changeCar} ></button>
<B carName={this.state.carName }/>
</div>
)
}
}
class B extends React.Component{
componentDidMount(){
console.log('componentDidMount');
}
//组件将要接收~新的~props时调用
componentWillReceiveProps(props){
console.log(props)
console.log('B-componentWillReceiveProps');
}
render(){
return(
<div>B,{this.props.carName}</div>
)
}
}
ReactDOM.render(<A/>,document.getElementById('test'))