1. 程式人生 > 其它 >React-Native 網路請求和監控

React-Native 網路請求和監控

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

####(一) 網路監控 我們用NetInfo模組來監聽網路狀態

#####新增監聽 設定兩個屬性用來記錄狀態值

constructor(props){
        super(props);
        this.state = {
            isConnected:null,
            connectInfo:'',
        };
    };
  • NetInfo.isConnected.addEventListener(eventName, handler) 在網路埠或者連結是呼叫監聽函式
  • NetInfo.addEventListener(eventName, handler) 在網路狀況/型別發生變化時呼叫此監聽函式。回撥的引數為上面列出的網路狀況/型別。 eventName:監聽事件名稱 handl調函式
  componentDidMount() {
        //新增網路是否連線的監聽者
        NetInfo.isConnected.addEventListener('isConnected', this._handleNetStatus);
        //新增網路狀態變化的監聽者
        NetInfo.addEventListener('statusChange', this._handleNetChange);


        //檢查網路狀態
        NetInfo.isConnected.fetch().done(
            (isConnected) => {
                this.setState({isConnected:isConnected});
            }

        );
        //檢查網路型別
        NetInfo.fetch().done( (netType) => {
            this.setState({
                connectInfo:netType
            });

        });


    };
移除網監聽

在componentWillUnmount()方法中移除監聽

  • removeEventListener(eventName, handler)
  • NetInfo.isConnected.removeEventListener(eventName, handler)
 componentDidUnMount() {
        //移除監聽
        NetInfo.isConnected.removeEventListener('isConnected', this._handleNetStatus);
        NetInfo.removeEventListener('statusChange', this._handleNetChange);
    };
    _handleNetStatus = (isConnected) => {
        console.log('First, is ' + (isConnected ? 'online' : 'offline'));

    };

    _handleNetChange = (status) => {

        console.log('Then, is ' + status);

    };

####(二) 網路請求 React Native提供了和web標準一致的Fetch API,用於滿足開發者訪問網路的需求 要從任意地址獲取內容的話,只需簡單地將網址作為引數傳遞給fetch方法即可(fetch這個詞本身也就是獲取的意思)

fetch('https://postman-echo.com/transform/collection')

Fetch還有可選的第二個引數,可以用來定製HTTP請求一些引數。你可以指定header引數,或是指定使用POST方法,又或是提交資料等等

        //地址
        let url = 'https://postman-echo.com/transform/collection';
        //協議
        let map = {
            method:'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        };
        //引數
        map.body=JSON.stringify({
                from:1,
                to:2,

            }
        );
//如果你的伺服器無法識別上面POST的資料格式,那麼可以嘗試傳統的form格式
        //   map.body = 'from=1&to=2';
        //發起請求
        fetch(url, map)
            .then((response) => response.text())
            .then((responseJson) => {
                alert(responseJson);

            })
            .catch((err) => {
                alert('伺服器返回錯誤:' + err + url+ map);
            });

別忘了catch住fetch可能丟擲的異常,否則出錯時你可能看不到任何提示。 程式碼地址:https://github.com/roycehe/react-native-100-Demos

不要的吝嗇你的讚賞和☆

轉載於:https://my.oschina.net/roycehe/blog/869865