[TOC]
# 生命周期
https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html
1. `componentWillMount`
在微信小程序中這一生命周期方法對應頁面的`onLoad`或 入口文件app中的 `onLaunch`
2. `componentDidMount`
在微信小程序中這一生命周期方法對應頁面的 `onReady` 或入口文件app中的 `onLaunch`,在 `componentWillMount`后執行
3. `componentDidShow`
在微信小程序中這一生命周期方法對應 `onShow`。小程序啟動,或從后臺進入前臺顯示時觸發。
4. `componentDidHide`
在微信小程序中這一生命周期方法對應 `onHide`
5. `componentDidCatchError`
錯誤監聽函數,在微信小程序中這一生命周期方法對應 `onError`
6. `componentDidNotFound`
頁面不存在監聽函數,在微信小程序中這一生命周期方法對應 `onPageNotFound`
7. `shouldComponentUpdate`
頁面是否需要更新
8. `componentWillUpdate`
頁面即將更新
9. `componentDidUpdate`
頁面更新完畢
10. `componentWillUnmount`
https://segmentfault.com/q/1010000011961146/
頁面退出,在微信小程序中這一生命周期方法對應 `onUnload`
```js
// Components
interface ComponentLifecycle<P, S> {
componentWillMount?(): void;
componentDidMount?(): void;
componentWillReceiveProps?(nextProps: Readonly<P>, nextContext: any): void;
shouldComponentUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean;
componentWillUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): void;
componentDidUpdate?(prevProps: Readonly<P>, prevState: Readonly<S>, prevContext: any): void;
componentWillUnmount?(): void;
componentDidShow?(): void;
componentDidHide?(): void;
componentDidCatchError?(err: string): void;
componentDidNotFound?(obj: PageNotFoundObject): void;
}
```
## 專屬的方法成員
在小程序中 ,頁面還有一些專屬的方法成員,如下:
1. `onPullDownRefresh`:頁面相關事件處理函數--監聽用戶下拉動作
2. `onReachBottom`:頁面上拉觸底事件的處理函數
3. `onShareAppMessage`:用戶點擊右上角轉發
4. `onPageScroll`:頁面滾動觸發事件的處理函數
5. `onTabItemTap`:當前是 tab 頁時,點擊 tab 時觸發
6. `componentWillPreload`:預加載,只在微信小程序中可用
## 微信小程序轉 Taro
`import withWeapp from '@tarojs/with-weapp'`
Taro 會將原始文件的生命周期鉤子函數**轉換為 Taro 的生命周期**,完整對應關系如下:
| Page.onLoad | componentWillMount |
| --- | --- |
| onShow | componentDidShow |
| onHide | componentDidHide |
| onReady | componentDidMount |
| onUnload | componentWillUnmount |
| onError | componentCatchError |
| App.onLaunch | componentWillMount |
| **Component.created** | componentWillMount |
| attached | componentDidMount |
| ready | componentDidMount |
| detached | componentWillUnmount |
| moved | 保留 |
## process.env.TARO_ENV
使用 `process.env.TARO_ENV` 可以幫助我們判斷當前的編譯環境,從而做一些特殊處理,目前它的取值有 `weapp` 、`swan` 、 `alipay` 、 `h5` 、 `rn` 五個。可以通過這個變量來書寫對應一些不同環境下的代碼,在編譯時會將不屬于當前編譯類型的代碼去掉,只保留當前編譯類型下的代碼,從而達到兼容的目的。例如想在微信小程序和 H5 端分別引用不同資源:
```
if (process.env.TARO_ENV === 'weapp') {
require('path/to/weapp/name')
}
else if (process.env.TARO_ENV === 'h5') {
require('path/to/h5/name')
}
```
我們知道了這個變量的用法后,就可以進行一些多端兼容了,下面舉兩個例子來詳細闡述
# 參考
[Taro深度開發實踐](https://aotu.io/notes/2018/11/30/taro_practice/index.html)