一、React生命週期
- getDefaultProps:初始化Props屬性,Props來自於父組件或者其他組件傳遞過來的。
- getInitialState:初始化我們當前組件的狀態。
- componentWillMount:組件在初始化之前會調用這個方法。
- render:渲染UI。
- componentDidMount:組件渲染完成之後會調用這個方法。
- componentWillReceiveProps:父組件的傳遞東西過來時會調用這個方法。
- shouldComponentUpdate:組件更新時調用。
- componnetWillUpdate:組件更新前調用。
- componentDidUppdate:組件更新後調用。
- componentWillUnmount:組件銷燬時調用
1.父組件Life.js
父組件爲Life.js,裏面有兩個按鈕,作用爲把當前組件的count屬性+1
import React from 'react';
import ChildLife from './ChildLife';
/**
* 父組件
*/
class Life extends React.Component {
//構造器
constructor(props){
super(props);
this.state = { //組件內的變量等都通過state來存取
count : 0
};
}
/**
* 點擊事件的第一種實現方式:
*/
addCount = ()=>{
this.setState({
count : this.state.count + 1
})
}
/**
* 點擊事件的第二種實現方式:
*/
addCountBindThis(){
this.setState({
count : this.state.count + 1
})
}
render() {
return (
<div>
<p>看一下React生命週期</p>
<button onClick={this.addCount}>按鈕1:不使用bind</button>
<button onClick={this.addCountBindThis.bind(this)}>按鈕2:使用bind</button>
<p>{this.state.count}</p>
<ChildLife parentCount = {this.state.count}></ChildLife>
</div>
)
}
}
export default Life;
2.子組件ChildLife.js
父組件傳遞父組件的count給子組件,名稱爲parentCount,子組件進行展示。
import React from 'react';
/**
* 子組件
*/
class ChildLife extends React.Component{
constructor(props){
super(props);
this.state={
count : 0
};
}
/** 生命週期們 **/
componentWillMount() { //組件在初始化之前會調用這個方法
console.log("componentWillMount() -> 組件在初始化之前會調用這個方法");
}
componentDidMount() { //組件渲染完成之後會調用這個方法
console.log("componentDidMount() -> 組件渲染完成之後會調用這個方法");
}
componentWillReceiveProps(newProps) { //父組件的傳遞東西過來時會調用這個方法
console.log("componentWillReceiveProps() -> 父組件的傳遞東西過來時會調用這個方法");
console.log(newProps.parentCount)
}
render() {
return(
<div>
<p>子組件:</p>
<p>{this.props.parentCount}</p>
</div>
)
}
}
export default ChildLife;
3.配置下路由讓我們能夠測試
項目是基於ant design pro2,修改config/router.config.js