Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native this.setState not working

I know there's already a similar question but there's no code shared in there.

Under navbarChanged() > if condition, I'm doing a this.setState. This is of type HomeTab but setState doesn't seem to be working.

Any clues/pointers?

class HomeTab extends React.Component {   constructor() {     super()      this.setState({       isNavBarHidden: false     });   }    updatePosition(lastPosition) {   }    navbarChanged() {     console.log("received navbar changed event", AppStore.navbarVisible());      if (AppStore.navbarVisible()) {       StatusBarIOS.setHidden(false)       this.setState({ isNavBarHidden: false})       // this.state.isNavbarHidden is still true here       this.render();     }     else {       StatusBarIOS.setHidden(true);       this.setState({ isNavBarHidden: true});       this.render();     }   }    componentDidMount() {     AppStore.addNavbarChangeListener( this.navbarChanged.bind(this) );   }    componentWillMount() {     StatusBarIOS.setHidden(false)     this.setState({ isNavBarHidden: false });   } } 

And here's my render() code:

  render() {     return (         <NavigatorIOS style={styles.container}             navigationBarHidden={this.state.isNavBarHidden}             ref="navigator"             initialRoute={{               title: 'Foo',               component: HomeScreen,               passProps: { parent: this }             }}         />     )   } 
like image 567
Abdo Avatar asked Jun 15 '15 18:06

Abdo


2 Answers

Don't explicitly call render. React will automatically do a re-render when state or props change, so there's no need for this. Also, where is your actual render method?

As for your problem well, setState is asynchronous and so trying to work with state directly after a setState call won't work as the update won't necessarily have run. Instead you can use the second argument to setState which is a callback:

this.setState({ myVal: 'newVal'}, function() {     // do something with new state }); 

This will be triggered after state has been set and after the component has been re-rendered.

like image 178
Colin Ramsay Avatar answered Sep 23 '22 06:09

Colin Ramsay


Instead of setState, use state as an instance member of the es6 class. the function setState can be called later own to ensure necessary re-renders.

  constructor() {     super()      this.state = {       isNavBarHidden: false     };   } 
like image 37
RKichenama Avatar answered Sep 22 '22 06:09

RKichenama