我正在React Native中构建一个天气应用程序,在应用程序启动时直接获取基于用户位置的天气预报。
由于此请求需要一些时间,因此我希望显示活动指示符,直到使用获取的数据更新状态。一切正常,指标在请求期间显示并在应该消失时消失,但是指示器的动画似乎存在一些问题,因为它几乎直接冻结并保持冻结直到它消失。有什么建议可能是错的吗?
应用程序的初始状态:
URL.createObjectURL
根据坐标获取位置:
this.state = {
searchedCity: '',
placeholder: 'Search city...',
city: '',
country: '',
temperature: null,
weatherCondition: null,
weatherDescription: null,
error: null,
icon: null,
isLoading: true,
};
}
获取天气状况并更新状态。 isLoading设置为false以隐藏活动指示符:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
position => {
this.getWeatherByLoc(position.coords.latitude, position.coords.longitude);
},
error => {
this.setState({
error: 'Error fetching weather conditions!'
})
}
)
}
渲染方法:
getWeatherByLoc(lat, lon) {
api.fetchWeatherByLoc(lat, lon).then((data) => {
this.setState({
temperature: data.main.temp,
city: data.name,
weatherCondition: data.weather[0].main,
weatherDescription: data.weather[0].description,
isLoading: false,
});
});
}
显示活动指标的方法:
render() {
const { weatherCondition, weatherDescription, temperature, city, country, isLoading } = this.state;
return (
<View style={styles.container}>
<Weather weatherCondition={weatherCondition} weatherDescription={weatherDescription} city={city} country={country} temperature={temperature}/>
{this.renderLoading()}
<View style={styles.inputContainer}>
<TextInput style={styles.textInputStyle}
onChangeText={(searchedCity) => this.setState({searchedCity}) }
onSubmitEditing={ () => this.setState(this.getWeather())}
placeholder = {this.state.placeholder}
clearTextOnFocus={true}
enablesReturnKeyAutomatically={true}
/>
</View>
)}</View>);
}