reactjs - React native changing state -
im learning react native, building simple weather application
in index.ios.js have:
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 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> ) } }
im updating weather icon state here:
<icon name={iconnames[this.state.weather]} size={80} color={'white'}/>
which changes icon expected, icon seems disappear after second, , when reload app same happens. icon appears disappears.
if hard code value this, icon stays there expected:
<icon name={'md-snow'} size={80} color={'white'}/>
your icon appears @ first time because setting default value in componentwillmount.
then, after component renders call componentdidmount , tries update state on getlocation method.
assuming icon disappears after renders, can problem in getlocation method.
by checking docs, looks have setup permissions use geolocation. make sure have allowed: https://facebook.github.io/react-native/docs/geolocation.html
then call fetchweather
method. couldn't understand did came from. check if it's working expected.
and piece error should be: this.setstate
. try adding console.log res.weather
check it's return. if returns null, try adding console.log(res)
check getting.
from may have following scenarios:
1) res.weather or res returning null. suggest check docs of method trying use, maybe forgot something. add console.logs make sure if code returning expected.
2) res.weather returns value doesn't exists icon same name. in case should use switch(res.weather) case
, set state correctly string based on return of weather
hope helps.
Comments
Post a Comment