一、組件的生命周期
1咳胃、生命周期函數(shù)介紹:
(1)初始化
【1】constructor
【2】componentWillMount(只執(zhí)行一次 )
【3】render
【4】componentDidMount(只執(zhí)行一次)
(2)運(yùn)行期
【1】state改變
【2】props變化
(3)結(jié)束期
【1】componentWillUnmount
2咏雌、定時(shí)器程序舉例:
class App extends Component {
state = {
count:10
};
//聲明周期一
render() {
const {count} = this.state;
return (
{this.state.count}
)
}
//生命周期二
componentDidMount(){
this.timer = setInterval(()=>{
const {count} = this.state;
if(count === 0) {
return clearInterval(this.timer);
}
this.setState({
count:count-1
});
}, 1000);
}
//聲明周期三
componentWillUnmount(){
clearInterval(this.timer);
}
}
3胆萧、生命周期函數(shù)總結(jié)
(1)render中只做渲染相關(guān)的操作
(2)隨組件加載只執(zhí)行一次的操作,放在WillMount或DidMount中
(3)聲明周期函數(shù)不能是阻塞的镊叁!
(4)記得在willUnmount中銷毀定時(shí)器和一些訂閱事件
(5)props發(fā)生變化柠辞,使用willReceiveProps來(lái)處理
4团秽、注意點(diǎn):
(1)定時(shí)器函數(shù)
【1】setTimeout只執(zhí)行一次
【2】setInterval循環(huán)執(zhí)行
(2)生命周期函數(shù)和自定義函數(shù)區(qū)別
【1】生命周期函數(shù)寫法:
renderResult=()=>{ }
【2】自定義函數(shù)寫法:
render() { }
5、如何在render中根據(jù)不同條件渲染不同結(jié)果?
6徙垫、何時(shí)用props讥裤,何時(shí)用state?
(1)子控件中姻报,props可以作為state的初始值
如
在render中己英,state = {
count: this.props.time
}
此時(shí),傳參只是第一次有效吴旋。
(2)子控件如何獲得變化后的props损肛?
componentWillReceiveProps(nextProps) {
this.setState({
});
}
二、組件間通信
1荣瑟、父組件向子組件通信治拿、子組件之間通信
(1)注意事項(xiàng):
【1】父組件以自身的state作為子組件的props;父組件調(diào)用setState笆焰,于是子組件的props相應(yīng)變化劫谅。
【2】Component中若使用state而不是props渲染,則使用componentWillReceiveProps生命周期函數(shù)