react-native系列(22)API篇:网络状态NetInfo与网络请求Fetch详解

网络状态NetInfo

NetInfo库的作用是检测当前是否联网及获取联网方式及网络牌照等信息。

要使用NetInfo库,需要先在AndroidManifest.xml中配置权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

要检测网络是否在线可以使用:

NetInfo.isConnected.fetch().then(isConnected => {
    console.log('网络状态:' + isConnected ? 'online' : 'offline');
});

// 事件监听
function handleFirstConnectivityChange(isConnected) {
    console.log('状态变化了,网络状态:' + isConnected ? 'online' : 'offline');
    NetInfo.isConnected.removeEventListener('connectionChange',handleFirstConnectivityChange);
}
NetInfo.isConnected.addEventListener('connectionChange',handleFirstConnectivityChange);

其中isConnected为true时表示当前已经联网。

要获取当前联网方式及网络牌照可以使用:

NetInfo.getConnectionInfo().then((connectionInfo) => {
    console.log('连接方式: ' + connectionInfo.type + ', 网络牌照: ' + connectionInfo.effectiveType);
});

// 事件监听
function handleFirstConnectivityChange(connectionInfo) {
    console.log('信息变化了, 连接方式: ' + connectionInfo.type + ', 网络牌照: ' + connectionInfo.effectiveType);
    NetInfo.removeEventListener('connectionChange',handleFirstConnectivityChange);
}
NetInfo.addEventListener('connectionChange', handleFirstConnectivityChange);

回调函数type的类型有:

  • none - 设备处于离线状态
  • wifi - 设备通过wifi联网,或者设备是iOS模拟器
  • cellular - 设备通过蜂窝数据流量联网
  • unknown - 联网状态异常

回调函数effectiveType的类型有:

  • 2g
  • 3g
  • 4g
  • unknown

贴上完整代码:

import React from 'react';
import { View, NetInfo, Button, Alert} from 'react-native';

class NetInfoAPI extends React.Component {

    // 检测网络状态
    checkNet = () => {
        NetInfo.isConnected.fetch().then(isConnected => {
            Alert.alert('提示','网络状态:' + isConnected ? 'online' : 'offline');
        });

        // 事件监听
        function handleFirstConnectivityChange(isConnected) {
            Alert.alert('提示','状态变化了,网络状态:' + isConnected ? 'online' : 'offline');
            NetInfo.isConnected.removeEventListener('connectionChange',handleFirstConnectivityChange);
        }
        NetInfo.isConnected.addEventListener('connectionChange',handleFirstConnectivityChange);
    }

    // 获取网络信息 
    getNetInfo = () => {
        NetInfo.getConnectionInfo().then((connectionInfo) => {
            Alert.alert('提示','连接方式: ' + connectionInfo.type + ', 网络牌照: ' + connectionInfo.effectiveType);
        });

        // 事件监听
        function handleFirstConnectivityChange(connectionInfo) {
            Alert.alert('提示','信息变化了, 连接方式: ' + connectionInfo.type + ', 网络牌照: ' + connectionInfo.effectiveType);
            NetInfo.removeEventListener('connectionChange',handleFirstConnectivityChange);
        }
        NetInfo.addEventListener('connectionChange', handleFirstConnectivityChange);
    }

    render(){
        return(
            <View>
                <Button 
                    onPress={this.checkNet}
                    title='检测网络状态'
                />
                <Button 
                    onPress={this.getNetInfo}
                    title='获取网络信息'
                />
            </View>
        );
    }
}

export default NetInfoAPI;

效果:

网络请求Fetch

app开发基本上都需要与后台进行数据交互,关于接口,一般使用的是Restful风格的API。Fetch请求返回的结果是一个Promise类型,如果使用链式写法(.then.catch),要记住,reject方法的作用,等同于抛出错误,无论哪个then中发生错误都可以在catch中捕获。关于Promise类型详细可以参考http://es6.ruanyifeng.com/#docs/promise。目前的官方对Fetch是还不支持中断请求操作。

下面是一段使用Fetch实现get请求和post请求的参考代码:

import React, {Component} from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';

class FetchAPI extends Component {

    // get请求-无参
    _getJson = () => {
        fetch('http://www.helloui.net/api/json/products.json')
            .then((resp) => resp.json())
            .then((json)=>{
                Alert.alert('请求成功:', JSON.stringify(json)); // json:Array(3) [Object, Object, Object]
            })
            .catch((error)=>{
                console.log(error);
            }
        );
    }

    // get请求-带参
    _getWithParam = () => {
        fetch('http://www.helloui.net/rn_get?name=admin')
            .then((resp) => resp.json())
            .then((json)=>{
                Alert.alert('请求成功:', JSON.stringify(json)); // json:Object {name: "admin"}
            })
            .catch((error)=>{
                console.log(error);
            }
        );
    }

    // post请求
    // 如果'Content-Type': 'application/x-www-form-urlencoded'格式
    // 则参数入参为字符串 body:JSON.stringify({name: 'admin'});
    // 或者 body: 'data='+ JSON.stringify({name: 'admin'});
    // 是否加 'data='前缀取决于后台获取请求体body的方式
    // 如果要连接本地服务器联调测试,请使用10.0.2.2代替localhost或127.0.0.1,如果跨域联调请使用cors
    _post = () => {
        let data = JSON.stringify({
            name:'admin'
        });
        const body = new FormData();
        body.append('data', data);
        fetch('http://www.helloui.net/rn_post', {
                method: 'POST',
                body,
                headers: {
                    'Content-Type':'multipart/form-data',
                    'Accept': 'application/json'
                }
            })
            .then((resp) => resp.json())
            .then((json)=>{
                Alert.alert('请求成功:', JSON.stringify(json)); // json:Object {name: "admin"}
            })
            .catch((error)=>{
                console.log(error);
            }
        );
    }

    render() {
        return (
            <View style={styles.containerStyle}>
                
                <TouchableOpacity 
                    onPress={this._getJson}
                    activeOpacity={0.8}
                >
                    <View style={styles.btnViewStyle}>
                        <Text style={styles.btnTextStyle}>GET JSON Fetch请求</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity 
                    onPress={this._getWithParam}
                    activeOpacity={0.8}
                >
                    <View style={styles.btnViewStyle}>
                        <Text style={styles.btnTextStyle}>GET WithParam Fetch请求</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity 
                    onPress={this._post}
                    activeOpacity={0.8}
                >
                    <View style={styles.btnViewStyle}>
                        <Text style={styles.btnTextStyle}>POST Fetch请求</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    containerStyle:{
        flex: 1
    },
    btnViewStyle: {
        backgroundColor: 'green',
        height: 100,
        borderWidth: 1,
        borderRadius: 10,
        justifyContent: 'center',
        alignItems: 'center'
    },
    btnTextStyle: {
        color: 'white',
        fontSize: 24
    }
});

export default FetchAPI;

其中http://www.helloui.net/api是我自己在阿里云测试用的服务器。效果:

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React中封装网络请求可以使用各种库,如axios、fetch等。下面是一个简单的示例,演示如何使用axios来封装网络请求: 1. 首先,安装axios库: ``` npm install axios ``` 2. 创建一个名为api.js的文件,用于封装所有的API请求: ```jsx import axios from 'axios'; // 封装GET请求 export const get = async (url, params) => { try { const response = await axios.get(url, { params }); return response.data; } catch (error) { console.error(error); throw error; } }; // 封装POST请求 export const post = async (url, data) => { try { const response = await axios.post(url, data); return response.data; } catch (error) { console.error(error); throw error; } }; ``` 3. 在需要发送网络请求的组件中使用封装的API方法: ```jsx import React, { useEffect, useState } from 'react'; import { get } from './api'; const MyComponent = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const result = await get('https://api.example.com/data'); setData(result); } catch (error) { // 处理错误 } }; fetchData(); }, []); if (!data) { return <div>Loading...</div>; } return ( <div> {/* 使用获取到的数据 */} {data.map((item) => ( <div key={item.id}>{item.name}</div> ))} </div> ); }; export default MyComponent; ``` 这是一个简单的示例,你可以根据实际需求进行扩展和修改。封装网络请求可以使代码更加模块化和可复用,同时也方便统一处理错误和请求拦截等操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值