W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
組件的生命周期函數(shù)在特殊的時(shí)間點(diǎn)由框架觸發(fā)。組件生命周期示意圖如下:
生命周期函數(shù)具體信息見(jiàn)下表:
函數(shù)名 | 參數(shù) | 說(shuō)明 | 最低版本 |
---|---|---|---|
onInit | - | 組件創(chuàng)建時(shí)觸發(fā) | 1.14.0 |
deriveDataFromProps | nextProps | 組件創(chuàng)建時(shí)和更新前觸發(fā) | 1.14.0 |
didMount | - | 組件創(chuàng)建完畢時(shí)觸發(fā) | - |
didUpdate | (prevProps,prevData) | 組件更新完畢時(shí)觸發(fā) | - |
didUnmount | - | 組件刪除時(shí)觸發(fā) | - |
注意:onInit
、deriveDataFromProps
自基礎(chǔ)庫(kù) 1.14.0
才支持,可以使用 my.canIUse('component2') 做兼容,并且,需要在開(kāi)發(fā)者工具中的 詳情 > 項(xiàng)目配置 中,勾選 component2。
onInit
在組件創(chuàng)建時(shí)觸發(fā)。在onInit中,可以進(jìn)行以下操作:
this.is
、this.$id
、this.$page
等屬性this.data
、this.props
等屬性this.setData
、this.$spliceData
修改數(shù)據(jù)// /components/index/index.js
Component({
data: {
counter: 0,
},
onInit() {
this.setData({
counter: 1,
is: this.is,
});
},
});
<!-- /components/index/index.axml -->
<view>{{counter}}</view>
<view>{{is}}</view>
當(dāng)組件在頁(yè)面上渲染后,頁(yè)面輸出如下:
1
/components/index/index
// /components/index/index.js
Component({
onInit() {
this.xxx = 2;
this.data = { counter: 0 };
},
});
<!-- /components/index/index.axml -->
<view>{{counter}}</view>
當(dāng)組件在頁(yè)面上渲染后,頁(yè)面輸出如下:
0
deriveDataFromProps
在組件創(chuàng)建和更新時(shí)都會(huì)觸發(fā)。
在deriveDataFromProps
中可以:
this.is
、this.$id
、this.$page
等屬性this.data
、this.props
等屬性this.setData
、this.$spliceData
修改數(shù)據(jù)nextProps
參數(shù)獲取將要更新的 props
參數(shù)// /components/index/index.js
Component({
data: {
counter: 5,
},
deriveDataFromProps(nextProps) {
if (this.data.counter < nextProps.pCounter) {
this.setData({
counter: nextProps.pCounter,
});
}
},
});
<!-- /components/index/index.axml -->
<view>{{counter}}</view>
// /pages/index/index.js
Page({
data: {
counter: 1,
},
plus() {
this.setData({ counter: this.data.counter + 1 })
},
});
<!-- /pages/index/index.axml -->
<my-component pCounter="{{counter}}" />
<button onTap="plus">+</button>
注意:本示例中點(diǎn)擊 + 按鈕,頁(yè)面上的 counter 會(huì)一直保持不變,直到 pCounter 的值大于 5。
didMount 為自定義組件首次渲染完畢后的回調(diào),此時(shí)頁(yè)面已經(jīng)渲染,通常在這時(shí)請(qǐng)求服務(wù)端數(shù)據(jù)。
Component({
data: {},
didMount() {
let that = this;
my.httpRequest({
url: 'http://httpbin.org/post',
success: function(res) {
console.log(res);
that.setData({name: 'xiaoming'});
}
});
},
});
didUpdate 為自定義組件數(shù)據(jù)更新后的回調(diào),每次組件數(shù)據(jù)變更的時(shí)候都會(huì)調(diào)用。
Component({
data: {},
didUpdate(prevProps, prevData) {
console.log(prevProps, this.props, prevData, this.data);
},
});
注意:
this.setData
會(huì)觸發(fā) didUpdate。this.setData
也會(huì)觸發(fā) didUpdate。didUnmount 為自定義組件被卸載后的回調(diào),每當(dāng)組件實(shí)例從頁(yè)面卸載的時(shí)候都會(huì)觸發(fā)此回調(diào)。
Component({
data: {},
didUnmount() {
console.log(this);
},
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: