我创建了一个从URL(对象数组)检索数据并将其显示在FlatList中的应用程序。
当前,启动应用程序时,数据正确显示(它们是异步检索的)。如果我切换到飞行模式,则显示消息“没有互联网连接”,但未显示我的AsyncStorage的数据(应用程序的背景为白色)。如果我禁用飞行模式,我的数据将再次显示。
class MontanteTab extends Component {
state = {
errors: null,
isLoading: true,
isConnected: true,
refreshing: false,
pronostics: [],
};
async componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
if (this.state.isConnected) {
await this.loadPronostics();
}
try {
this.setState({pronostics: JSON.parse(await AsyncStorage.getItem(Keys.pronosticsMontante))});
} catch (error) {
console.log(error);
}
}
handleConnectivityChange = isConnected => {
console.log(isConnected);
this.setState({isConnected: isConnected});
};
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
}
onRefresh = () => {
console.log('refreshing...');
this.setState({refreshing: true});
this.loadPronostics();
this.setState({refreshing: false});
console.log('refreshed...');
};
loadPronostics() {
this.setState({isLoading: true, error: null});
return axios.get(AppConfig.apiUrl + 'montante').then(async response => {
await AsyncStorage.setItem(Keys.pronosticsMontante, JSON.stringify(response.data));
this.setState({isLoading: false});
}).catch(error => {
this.setState({isLoading: false, error: error.response});
console.log(error);
});
}
render() {
if (this.state.isLoading === true) {
return (
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
if (!this.state.isConnected) {
return (
<OfflineNotice/>
)
}
return (
<View>
<FlatList
data={this.state.pronostics}
extraData={this.state.pronostics}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this.onRefresh.bind(this)}
title="Glisser pour rafraîchir"
tintColor="#fff"
titleColor="#fff"
/>
}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => (
<ListItem
key={item.id}
roundAvatar
badge={{
value: item.statut,
textStyle: {color: '#fff'},
containerStyle: {marginRight: 0, backgroundColor: item.couleur}
}}
avatar={<Image
source={{uri: AppConfig.imagesPronosticsUrl + item.image}}
style={{borderRadius: 50, height: 50, width: 50, overflow: 'hidden'}}/>}
title={item.competition}
subtitle={item.equipe_domicile + ' - ' + item.equipe_exterieur}
onPress={() => this.props.navigation.navigate('PronosticsDetails', {
item,
})}
/>
)}
/>
</View>
);
}
}
当没有更多的Internet连接时,如何显示我的AsyncStorage数据?
还有一个额外的问题:当我在API中添加新数据并拉动刷新FlatList时,FlatList不会更新。为什么要这样?
答案 0 :(得分:1)
如果要在没有互联网连接但将其存储在本地的情况下显示单位列表,请替换:
if (!this.state.isConnected) {
return (
<OfflineNotice/>
)
}
具有:
if (!this.state.isConnected && this.state.pronostics.length === 0) {
return (
<OfflineNotice/>
)
}
状态更改后,例如this.setState
,React视图将刷新。如果要在“拉出”数据后手动强制进行更新,请使用this.forceUpdate
。