Abdo Abdo - 3 months ago 33
React JSX Question

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 }
}}
/>
)
}

Answer

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.