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 } }} /> ) }
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.
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 }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With