簡體   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