【问题标题】:How can i setInterval outside class extends Component?我如何 setInterval 外部类扩展组件?
【发布时间】:2020-01-15 21:27:47
【问题描述】:

我想 setInterval 连接检查,但它不适合我。有人可以向我解释为什么以及我该怎么做吗?谢谢!

import React, { Component } from 'react';
import { StyleSheet, TouchableWithoutFeedback, Keyboard, Text, View, TouchableOpacity, Image, Alert, TextInput, FlatList, Button, RefreshControl } from 'react-native';
import NetInfo from "@react-native-community/netinfo";

import * as signalR from '@aspnet/signalr';

const hubUrl = '/chatHub';
const hub = new signalR.HubConnectionBuilder()
    .withUrl(hubUrl)
    .configureLogging(signalR.LogLevel.Information)
    .build();

setInterval(NetInfo.getConnectionInfo().then((connectionInfo) => {
    alert(
       'Initial, type: ' +
        connectionInfo.type +
        ', effectiveType: ' +
       connectionInfo.effectiveType,
     );
  }),1000);

export default class ChatScreen extends Component { }

【问题讨论】:

    标签: react-native react-native-community-netinfo


    【解决方案1】:

    调用componentDidMount()中的setInterval

    您为什么不使用 NetInfo 事件侦听器?有什么特殊原因吗?

    NetInfo.addEventListener(state => {
      console.log("Connection type", state.type);
      console.log("Is connected?", state.isConnected);
    });
    

    【讨论】:

    • 是的,因为我的 hub.start();只能调用一次。所以我必须在类组件之外写它。但是当连接丢失时,我无法调用 hub.start();再次。
    • 您可以非常轻松地检查与侦听器的连接状态。每次连接发生变化(连接或断开),您都可以调用特定的代码。每次连接更改时都会调用侦听器回调。
    • 谢谢,我知道,但是如果我检查状态以在类组件中调用hub.start(); 我的hub.start(); 将在我再次打开它时发生冲突
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多