如何删除网络请求失败错误屏幕并在react-native中显示消息“无互联网连接”

时间:2018-06-07 07:34:39

标签: react-native

如果没有互联网连接,如何删除网络请求失败错误屏幕并显示消息“无互联网连接”,以便在react-native中获得更好的用户体验。

4 个答案:

答案 0 :(得分:0)

您可以在React-Native中使用NetInfo来检查网络状态。这是链接: https://facebook.github.io/react-native/docs/netinfo.html

这是示例代码:

 NetInfo.getConnectionInfo().then((connectionInfo) => {
            if (connectionInfo.type === 'none') {
                alert("No internet connection")
            } else {
                // online
               // do something

            }
        });

答案 1 :(得分:0)

在这里,我写了一个处理互联网状态问题的组件,请参考:

import React, { Component } from "react";
import {
  View,
  NetInfo,
  Animated,
  Easing,
  Dimensions,
  Platform,
  AppState
} from "react-native";
// import { colors, Typography, primaryFont } from "../../Config/StylesConfig";
import { connect } from "react-redux";
import { changeConnectionStatus } from "../../actions/authActions";
import CustomText from "./CustomText";
import firebaseHelper from "../../helpers/firebaseHelper";

const { width } = Dimensions.get("window");
class InternetStatusBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isNetworkConnected: true
    };
    this._updateConnectionStatus = this._updateConnectionStatus.bind(this);
    this.positionValue = new Animated.Value(-26);
    this.colorValue = new Animated.Value(0);
    this.isMount = true;
    this.isOnline = true;
  }

  _handleAppStateChange = nextAppState => {
    if (nextAppState.match(/inactive|background/) && this.isOnline) {
      firebaseHelper.goOffline();
      // console.log("offline");
      this.isOnline = false;
    } else if (nextAppState === "active" && this.isOnline === false) {
      firebaseHelper.goOnline();
      // console.log("online");
      this.isOnline = true;
    }
  };
  componentDidMount() {
    AppState.addEventListener("change", this._handleAppStateChange);
    // NetInfo.isConnected.fetch().done(isNetworkConnected => {
    //   this._updateConnectionStatus(isNetworkConnected);
    // });
    NetInfo.isConnected.addEventListener(
      "connectionChange",
      this._updateConnectionStatus
    );
  }

  componentWillUnmount() {
    AppState.removeEventListener("change", this._handleAppStateChange);
    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this._updateConnectionStatus
    );
  }

  _updateConnectionStatus(isNetworkConnected) {
    // this.setState({ isNetworkConnected });
    if (this.isMount) {
      this.isMount = false;
    } else {
      if (isNetworkConnected) {
        this.animateColorChange(isNetworkConnected);
        setTimeout(() => {
          this.animateErrorView(isNetworkConnected);
        }, 1000);
      } else {
        this.animateErrorView(isNetworkConnected);
        this.colorValue = new Animated.Value(0);
      }
    }
    // this.props.changeConnectionStatus(isNetworkConnected);
  }

  // componentWillReceiveProps = nextProps => {
  //   if (
  //     nextProps.isInternetConnected &&
  //     nextProps.isInternetConnected != this.state.isInternetConnected
  //   ) {
  //     const date = new Date();
  //     Actions.refresh({ refreshContent: date.getTime() });
  //   }
  // };

  animateErrorView(connected) {
    Animated.timing(this.positionValue, {
      toValue: connected ? -40 : Platform.OS === "ios" ? 20 : 0,
      easing: Easing.linear,
      duration: 600
    }).start();
  }

  animateColorChange(connected) {
    Animated.timing(this.colorValue, {
      toValue: connected ? 150 : 0,
      duration: 800
    }).start();
  }

  render() {
    return (
      <Animated.View
        style={[
          {
            position: "absolute",
            backgroundColor: this.colorValue.interpolate({
              inputRange: [0, 150],
              outputRange: ["rgba(0,0,0,0.6)", "rgba(75, 181, 67, 0.8)"]
            }),
            zIndex: 1,
            width: width,
            top: 0,
            transform: [{ translateY: this.positionValue }]
          }
        ]}
      >
        <View
          style={[
            {
              padding: 4,
              flexDirection: "row",
              flex: 1
            }
          ]}
        >
          <CustomText
            style={{
              fontSize: 12,
              textAlign: "center",
              flex: 1
            }}
          >
            {this.state.isInternetConnected ? "Back online" : "No connection"}
          </CustomText>
        </View>
      </Animated.View>
    );
  }
}

const mapStateToProps = state => {
  return {
    isInternetConnected: state.user.isInternetConnected
  };
};

export default connect(mapStateToProps, { changeConnectionStatus })(
  InternetStatusBar
);

答案 2 :(得分:0)

Snackbar是传达此信息的好方法。看看这个图书馆: https://github.com/9gag-open-source/react-native-snackbar-dialog

答案 3 :(得分:0)

简单易用,具有良好的用户体验 使用&#34; react-native-offline-status&#34; 参考: https://github.com/rgabs/react-native-offline-status