在axios请求数据过程中使用异步操作,在请求开始前显示ActivityIndicator,在请求结束后隐藏ActivityIndicator。
代码示例:
import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, } from 'react-native'; import axios from 'axios';
export default class App extends Component { constructor(props) { super(props); this.state = { isLoading: true, data: [], }; }
async componentDidMount() { this.setState({ isLoading: true }); try { const response = await axios.get('https://example.herokuapp.com/data'); // 处理从服务器返回的数据 this.setState({ data: response.data }); } catch (error) { console.error(error); } this.setState({ isLoading: false }); }
render() { const { isLoading, data } = this.state;
if (isLoading) {
return (
);
}
return (
(
{item.title}
)}
keyExtractor={item => item.id}
/>
);
} }