这个组件已经在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 );