首页 > 解决方案 > 活动指示器在请求期间冻结

问题描述

我正在 React Native 中构建一个天气应用程序,其中基于用户位置的天气预报是在应用程序启动时直接获取的。

由于此请求需要一些时间,我想显示一个活动指示器,直到使用获取的数据更新状态。一切正常,指示器在请求期间显示并在它应该消失时消失,但是指示器的动画似乎存在一些问题,因为它几乎直接冻结并保持冻结直到它消失。有什么建议可能是错的吗?

App的初始状态:

   this.state = {
  searchedCity: '',
  placeholder: 'Search city...',
  city: '',
  country: '',
  temperature: null,
  weatherCondition: null,
  weatherDescription: null,
  error: null,
  icon: null,
  isLoading: true,
  };
}

根据坐标获取位置:

componentDidMount() {

 navigator.geolocation.getCurrentPosition(    
   position => {
  this.getWeatherByLoc(position.coords.latitude, position.coords.longitude);
   },
   error => {
    this.setState({
       error: 'Error fetching weather conditions!'  
     })
   }
 )
}

获取天气状况并更新状态。isLoading 设置为 false 以隐藏活动指示器:

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>);
}

显示活动指标的方法:

  renderLoading() {
const {isLoading} = this.state;  
  if(isLoading) {
    return (
  <View style={styles.loading}><BarIndicator color="white" animating = {isLoading}/> </View> 
    )
} else {
  return (null)
}
}

标签: react-nativesetstateactivity-indicator

解决方案


推荐阅读