Reactjs 反应本机变化状态

Reactjs 反应本机变化状态,reactjs,react-native,Reactjs,React Native,通过构建一个简单的天气应用程序,我正在学习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 {

通过构建一个简单的天气应用程序,我正在学习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>
    )
  }
}
const图标名={
清楚:“md sunny”,
雨:“md雨”,
雷暴:“md雷暴”,
云:“md多云”,
斯诺:“md斯诺”,
毛毛雨:“md雨伞”
}
类应用程序扩展组件{
组件willmount(){
//加载组件之前先加载
此.state={
温度:0,,
天气:“晴朗”
}
}
componentDidMount(){
//首次加载构件后的加载
这个文件名为getLocation()
}
getLocation(){
navigator.geolocation.getCurrentPosition(
(posData)=>fetchWeather(posData.coords.latitude,posData.coords.longitude)
.然后(res=>this.setState({
温度:res.temp,
天气:res.weather
})),
(错误)=>警报(错误),
{超时:10000}
)
}
render(){
返回(
{this.state.temp}}
下雨
雨
)
}
}
我正在更新此处的天气图标状态:

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

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

如果我像这样硬编码值,图标将按预期保持在那里:

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

您的图标第一次出现,因为您正在组件willmount中设置默认值

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

假设图标在渲染后消失,我们可以说问题出在getLocation方法中

通过检查文档,您似乎必须设置一些使用地理位置的权限。只需确保您允许:

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

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

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

1) 您的res.weather或res返回空值。然后我建议你检查一下你正在尝试使用的这个方法的文档,也许你忘了什么。还要添加一些console.log,以确保您的代码是否按预期返回了所有内容

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


希望有帮助。

是否可能
res.weather
不是
iconNames
对象的属性之一?@PatrikPrevuznak我在控制台中放置了一些日志,并返回正确的名称。。。它确实出现了几秒钟,然后消失了谢谢你的帮助。。我输入了一些日志,数据似乎返回了预期值,该值在weather对象中。您可以尝试删除超时吗?