React Native Expo App中RefreshView的超时

时间:2019-08-25 20:29:55

标签: javascript reactjs react-native axios expo

我当前的React Native Expo应用程序有一个实现ScrollView的{​​{1}}。用户拉下RefreshControl将导致执行ScrollView函数,该函数依次调用动作创建者onRefresh,该动作创建者使用getSpotPrices查询API。

问题:如果出现网络问题,axios函数将花费很长时间。因此,需要实现axios.get()axios.get()之外的计时。

如何在onRefresh中实现超时功能?

/src/containers/main.js

RefreshControl

/src/actions/index.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, RefreshControl } from 'react-native';

import MyList from '../components/MyList';
import { getSpotPrices } from '../actions';

class RefreshableList extends Component {

    onRefresh = () => {
        this.props.getSpotPrices();
    }

    render() {
        return (
            <ScrollView 
                refreshControl={
                    <RefreshControl 
                        refreshing={this.props.isLoading}
                        onRefresh={this._onRefresh}
                    />
                }>
                <MyList />
            </ScrollView>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        isLoading: state.currencies.isLoading,
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        getSpotPrices: () => dispatch(getSpotPrices()),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(RefreshableList);

/src/reducers/currencies.js

import api from "../utils/api";
import * as types from "../types";
import Axios from "axios";

const getSpotPrice = async () => {
  try {
    const res = await Axios.get(`https://api.coinbase.com/v2/prices/spot`);
    return parseFloat(res.data.data.amount);
  } catch (err) {
    throw new Error(err);
  }
};

export const getSpotPrices = () => async dispatch => {
  try {
    const price = await getSpotPrice();
    dispatch({
      type: types.CURRENCIES_SET,
      payload: price
    });
  } catch (err) {
    dispatch({
      type: types.CURRENCIES_FAILED_FETCH,
      payload: err.toString()
    });
  } finally {
    dispatch({
      type: types.CURRENCIES_IS_LOADING,
      payload: false
    })
  }
};

1 个答案:

答案 0 :(得分:0)

  1. 检查用户是否已使用react-native-netinfo library

    连接了互联网

    NetInfo.fetch()。then(state => {   console.log(“连接类型”,state.type);   console.log(“是否已连接?”,state.isConnected);   this.setState({connected:state.isConnected}); });

    //订阅 const unsubscribe = NetInfo.addEventListener(state => {   console.log(“连接类型”,state.type);   this.setState({connected:state.isConnected}); }); //退订 unsubscribe(); <-在componentwillunmount中完成此操作

  2. 在所有api调用中添加超时通常是一个好习惯,在axios中,您可以轻松地添加一个超时选项,例如:

await axios.get(url, { headers, timeout: 5000 })

因此,在您的情况下,将axios调用修改为

await Axios.get( https://api.coinbase.com/v2/prices/spot , { timeout: 5000 } );

我设置了5秒钟的超时时间,您可以根据需要修改参数。