繁体   English   中英

响应本机更改状态

[英]React native changing state

我通过构建一个简单的天气应用程序来学习本地反应

在我的index.ios.js中,我有:

const iconNames = {
  Clear: 'md-sunny',
  Rain: 'md-rainy',
  Thunderstorm: 'md-thunderstorm',
  Clouds: 'md-cloudy',
  Snow: 'md-snow',
  Drizzle: 'md-umbrella'
}

class App extends Component {

  componentWillMount() {
    //loads before component loaded
    this.state = {
      temp: 0,
      weather: 'Clear'
    }
  }

  componentDidMount(){
    //loads after Component loads for first time
    this.getLocation()
  }

  getLocation() {
    navigator.geolocation.getCurrentPosition(
      (posData) => fetchWeather(posData.coords.latitude,posData.coords.longitude)
        .then(res => this.setState({
          temp:res.temp,
          weather:res.weather
        })),
      (error) => alert(error),
      {timeout:10000}
    )
  }

  render() {
    return(
      <View style={styles.container}>
      <StatusBar hidden={true}/>
        <View style={styles.header}>
          <Icon name={iconNames[this.state.weather]} size={80} color={'white'}/>
          <Text style={styles.temp}>{this.state.temp}°</Text>
        </View>
        <View style={styles.body}>
          <Text>its raining</Text>
          <Text style={styles.subtitle}>rain</Text>
        </View>
      </View>
    )
  }
}

我在这里更新天气图标状态:

<Icon name={iconNames[this.state.weather]} size={80} color={'white'}/>

哪个按预期更改了图标,但是图标似乎在一秒钟后消失了,当我重新加载应用程序时,也会发生同样的情况。 图标出现,然后消失。

如果我对这样的值进行硬编码,则图标将按预期停留在该位置:

<Icon name={'md-snow'} size={80} color={'white'}/>

之所以会出现图标,是因为您正在componentWillMount中设置默认值。

然后,在组件呈现之后,您调用componentDidMount并尝试更新getLocation方法上的状态。

假设Icon呈现后消失了,可以说问题出在您的getLocation方法中。

通过检查文档,您似乎必须设置一些权限才能使用地理位置。 只需确保已允许: https : //facebook.github.io/react-native/docs/geolocation.html

然后,您调用fetchWeather方法。 我不明白它是从哪里来的。 检查它是否按预期工作。

最后是错误应该出现的部分: this.setState 尝试将console.log添加到您的res.weather以检查返回结果。 如果返回null,请尝试添加console.log(res)来检查得到的内容。

由此,您可能会遇到以下情况:

1)您的res.weather或res返回null。 然后,我建议检查您尝试使用的此方法的文档,也许您忘记了一些东西。 还添加一些console.logs以确保您的代码是否按预期返回了所有内容。

2)您的res.weather返回的值不存在具有相同名称的图标。 在这种情况下,您应该使用switch(res.weather) case并根据天气的返回值使用正确的字符串设置状态

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM