簡體   English   中英

React Native:無法讀取未定義的屬性“ isConnected”(檢測應用程序連接)

[英]React Native : Cannot read property 'isConnected' of undefined (detect app connection)

我需要在我的應用中檢查用戶與互聯網的連接。 我嘗試使用NetInfo,但出現此錯誤:

無法讀取未定義的屬性“ isConnected”

我還在AndroidManifest.xml文件中添加了權限,但這沒有幫助。

這是我的代碼:

NetInfo.isConnected.fetch().then(isConnected => {
    if (isConnected) {
        this.setState({
            loading: true,
        })
        var url = 'https://api.apixu.com/v1/current'+this.state.cityname
        return fetch(url)

            .then((data) => data.json())
            .then((datajson) => {
                this.setState({
                    loading: false,
                    fetched: true,
                })
                console.log(this.state.localtime)
            })

            .catch((error) => { console.error(error) })
    } else {
        Alert.alert("You are offline!");
    }

是什么導致此問題?

import {NetInfo} from 'react-native';


constructor(props) {
            super(props);
            this.state = {
                isNetConnected: true, 
            }
        }

async componentDidMount() {
    NetInfo.isConnected.addEventListener(
                'connectionChange',
                this._handleConnectivityChange

            );

            NetInfo.isConnected.fetch().done((isConnected) => {

              if(isConnected == true)
              {
                this.setState({isNetConnected: true})
              }
              else
              {
                this.setState({isNetConnected: false})
              }

            });                


        }

_handleConnectivityChange = (isConnected) => {

            if(isConnected == true)
            {
                this.setState({isNetConnected: true})
                this.getActivitiesAndNotifications()               
            }
            else
            {
                this.setState({isNetConnected: false})
            }
        };

像這樣使用。 現在,如果沒有任何互聯網連接,“ isNetConnected”將觸發

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM