我有api.js,其中我要编写服务调用逻辑,而home.js,我要显示从API获取数据。但是我越来越难以在home.js中调用函数并从api.js类中获取数据。
api.js
import axios from 'axios';
import * as myConstant from '../common/Constants';
export default async function fetchInfo() {
axios
.get(myConstant.API + 'albums', {timeout: myConstant.TIMEOUT} )
.then((response) => {
const items = response.data.items;
return items;
})
.catch(err => {
this.setState({isLoading: false, apiLoadingError: true})
});
}
home.js
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native-paper';
import {
Text, View, TouchableOpacity, FlatList
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import axios from 'axios';
import styles from '../style/Home.component.style';
import ErrorAlert from '../common/ErrorAlert';
import * as myConstant from '../common/Constants';
import fetchInfo from '../component/API';
export default class HomeScreen extends Component {
// For to Navigation header
static navigationOptions = () => ({
headerTitle: 'Album List',
});
constructor(props) {
super(props);
this.state = {
isLoading: true,
apiLoadingError: false,
items: []
};
}
async componentDidMount() {
**await fetchInfo().then((items) => this.setState({ items }));** NOT working for me ... how to get data here
}
FlatListItemSeparator = () => (
<View style={styles.flatListItemSeparator} />
)
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, paddingTop: 30 }}>
<ActivityIndicator animating={true} size='large' />
</View>
);
}
if (this.state.apiLoadingError) {
return (
<ErrorAlert />
);
}
return (
<View style={styles.MainContainer} >
<FlatList
data={ this.state.items }
testID='AlbumList'
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({ item }) => <View style={styles.listRowContainer}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ThumbnailViewScreen', {
albumID: item.id,
})} style={styles.listRow}>
<View style={styles.listTextNavVIew}>
<Text style={styles.albumTitle}> {console.log(fetchInfo().then((items) => this.setState({ items })))} </Text>
<Ionicons name='md-arrow-dropright' style={styles.detailArrow} />
</View>
</TouchableOpacity>
</View>
}
keyExtractor = { (item, index) => index.toString() }
/>
</View>
);
}
}
答案 0 :(得分:1)
我认为您发现的问题是您没有在fetchInfo中返回诺言,因此您在进行.then
时无法获取数据
import axios from 'axios';
import * as myConstant from '../common/Constants';
export default async function fetchInfo() {
return axios // IMPORTANT THE RETURN HERE
.get(myConstant.API + 'albums', {timeout: myConstant.TIMEOUT} )
.then((response) => {
const items = response.data.items;
return items;
})
.catch(err => {
this.setState({isLoading: false, apiLoadingError: true})
});
}
答案 1 :(得分:0)
您可以通过以下方式在React Native
中导出并调用函数:
api.js
const FetchInfo = {
fetchInfos: async function() {
//your function code
}
}
export default FetchInfo;
home.js
import FetchInfo from '../component/API';
//you call the function like this
FetchInfo.fetchInfos()