這個組件已經在RN剛出來(倆平台同時支持)的時候就已經存在了,用法大家都已經很熟悉了,但是在0.48+版本中,出現了一些變化,前面的用法都會過期
主要完善了兩個方面的問題
- 目前的NetInfo API是分平台的.在iOS和Android平台上返回完全不同的值.
- 目前的NetInfo API無法判定連接的手機網絡是 2g, 3g, 還是 4g.
貢獻者為了不造成breaking changes,所以直接新增新的api,將前面的api改為黃色警告
- `fetch`方法過時了,用`getConnection`替代 - `change`事件過時了,用`connectionchange`替代. - `fetch`/`change`過時了,用`getConnection`/`connectionchange`替代。返回的枚舉值也變了。具體查看下面的值
ConnectionType(設備的網絡類型):
跨平台:
- none
- 設備處於離線狀態。
- wifi
- 設備處於聯網狀態且通過wifi鏈接,或者是一個iOS的模擬器。
- cellular
- 設備是通過Edge、3G、WiMax或是LTE網絡聯網的。
- unknown
- 發生錯誤,網絡狀況不可知
Android平台:
- bluetooth
- 藍牙數據連接
- ethernet
- 以太網數據連接
- wimax
- WiMAX數據連接
EffectiveConnectionType(無線網絡類型) :
- 2g
- 3g
- 4g
- unknown
用法:
NetInfo.getConnectionInfo().then((connectionInfo) => { console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType); }); function handleFirstConnectivityChange(connectionInfo) { console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType); NetInfo.removeEventListener( 'connectionChange', handleFirstConnectivityChange ); } NetInfo.addEventListener( 'connectionChange', handleFirstConnectivityChange );
方法:
static addEventListener(eventName, handler) 添加一個事件監聽.支持如下事件: connectionChange: Fires when the network status changes. The argument to the event handler is an object with keys: type: ConnectionType類型 (已在上面列出) effectiveType: EffectiveConnectionType類型 (已在上面列出) change: This event is deprecated. Listen to connectionChange instead. Fires when the network status changes. The argument to the event handler is one of the deprecated connectivity types listed above.
static removeEventListener(eventName, handler) Removes the listener for network status changes.
static fetch()
This function is deprecated. Use getConnectionInfo
instead. Returns a promise that resolves with one of the deprecated connectivity types listed above.
static getConnectionInfo() Returns a promise that resolves to an object with type and effectiveType keys whose values are a ConnectionType and an EffectiveConnectionType, (described above), respectively. static isConnectionExpensive()
屬性:
isConnected: ObjectExpression An object with the same methods as above but the listener receives a boolean which represents the internet connectivity. Use this if you are only interested with whether the device has internet connectivity.
isConnected
適用於所有平台.異步獲取一個 boolean 類型的值判定是否連接到網絡.
NetInfo.isConnected.fetch().then(isConnected => { console.log('First, is ' + (isConnected ? 'online' : 'offline')); }); function handleFirstConnectivityChange(isConnected) { console.log('Then, is ' + (isConnected ? 'online' : 'offline')); NetInfo.isConnected.removeEventListener( 'change', handleFirstConnectivityChange ); } NetInfo.isConnected.addEventListener( 'change', handleFirstConnectivityChange );