转:/yangysng07/article/details/51583604
React Native 获取网络状态 NetworkInfo
React-native提供了了一个NetInfo类用来获取和监听网络状态。
属性与方法
-
(eventName:ChangeEventName,handler:Function) 静态方法,用设置网络变化事件监听器,同时需要传入回调的处理方法
-
(eventName:ChangeEventName,handler:Function) 静态方法, 用于移除网络事件变化监听器
-
() 静态方法 检测当前网络连接状态
-
(callback:(metered:?boolean,error?:string)=>void) 静态方法,检测当前连接的网络是否需要计费
-
:ObjectExpression 当前网络是否连接的属性
构造工具类
/**
* 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) =>{
().done(
(isConnected) => {
callback(isConnected);
}
);
}
/***
* 移除网络状态变化监听
* @param tag
* @param handler
*/
const removeEventListener = (tag,handler) => {
(tag, handler);
}
/***
* 添加网络状态变化监听
* @param tag
* @param handler
*/
const addEventListener = (tag,handler)=>{
(tag, handler);
}
export default{
checkNetworkState,
addEventListener,
removeEventListener,
NOT_NETWORK,
TAG_NETWORK_CHANGE
}
- 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
使用
import NetWorkTool from '../../utils/NetWorkTool'
handleMethod(isConnected){
('test', (isConnected ? 'online' : 'offline'));
}
constructor(props) {
super(props);
((isConnected)=>{
if(!isConnected){
(NetWorkTool.NOT_NETWORK);
}
});
}
componentWillMount() {
(NetWorkTool.TAG_NETWORK_CHANGE,this.handleMethod);
}
componentWillUnmount() {
(NetWorkTool.TAG_NETWORK_CHANGE,this.handleMethod);
}
- 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