转:http://blog.csdn.net/yangysng07/article/details/51583604
React Native 获取网络状态 NetworkInfo
React-native提供了了一个NetInfo类用来获取和监听网络状态。
-
1.addEventListener(eventName:ChangeEventName,handler:Function) 静态方法,用设置网络变化事件监听器,同时需要传入回调的处理方法
-
2.removeEventListener(eventName:ChangeEventName,handler:Function) 静态方法,用于移除网络事件变化监听器
-
3.fetch() 静态方法 检测当前网络连接状态
-
4.isConnectionExpensve(callback:(metered:?boolean,error?:string)=>void) 静态方法,检测当前连接的网络是否需要计费
-
5.isConnected :ObjectExpression 当前网络是否连接的属性
构造工具类
NetWorkTool.js
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
/** * Created by eleven on 16/6/3. */
import React,{
NetInfo
} from
'react-native';
const NOT_NETWORK =
"网络不可用,请稍后再试";
const TAG_NETWORK_CHANGE =
"NetworkChange";
/*** * 检查网络链接状态 * @param callback */
const checkNetworkState = (callback) =>{
NetInfo.isConnected.fetch().done(
(isConnected) => {
callback(isConnected);
}
);
}
/*** * 移除网络状态变化监听 * @param tag * @param handler */
const removeEventListener = (tag,handler) => {
NetInfo.isConnected.removeEventListener(tag,handler);
}
/*** * 添加网络状态变化监听 *const addEventListener = (tag,handler)=>{
NetInfo.isConnected.addEventListener(tag,handler);
}
export default{
checkNetworkState,addEventListener,removeEventListener,NOT_NETWORK,TAG_NETWORK_CHANGE
}
使用Component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
import NetWorkTool from '../../utils/NetWorkTool'
handleMethod(isConnected){
console.log('test',(isConnected ? 'online' : 'offline'));
}
constructor(props) {
super(props);
NetWorkTool.checkNetworkState((isConnected)=>{
if(!isConnected){
Toast.show(NetWorkTool.NOT_NETWORK);
}
});
}
componentWillMount() {
NetWorkTool.removeEventListener(NetWorkTool.TAG_NETWORK_CHANGE,this.handleMethod);
}
componentWillUnmount() {
NetWorkTool.removeEventListener(NetWorkTool.TAG_NETWORK_CHANGE,136); Box-sizing: border-Box;">this.handleMethod);
}