反应原生状态

时间:2017-09-10 15:29:49

标签: reactjs react-native

通过构建简单的天气应用程序,我的学习反应原生

在我的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'}/>

1 个答案:

答案 0 :(得分:1)

您的图标是第一次出现,因为您在componentWillMount中设置了默认值。

然后,在组件渲染后,您调用componentDidMount并尝试更新getLocation方法的状态。

假设图标在渲染后消失,我们可以说问题出在你的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.log以确保您的代码是否按预期返回所有内容。

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

希望它有所帮助。

相关问题