我知道已经有一个类似的问题,但是没有分享的代码.
@H_403_14@
不要显式调用render.当状态或道具改变时,React会自动执行重新渲染,所以没有必要.此外,您的实际渲染方法在哪里?
在navbarChanged()>如果条件,我正在做一个this.setState.这是HoMetab的类型,但setState似乎没有工作.
任何线索/指针?
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 }); } }
这里是我的render()代码:
render() { return ( <NavigatorIOS style={styles.container} navigationBarHidden={this.state.isNavBarHidden} ref="navigator" initialRoute={{ title: 'Foo',component: HomeScreen,passProps: { parent: this } }} /> ) }
对于您的问题,setState是异步的,所以在setState调用后,直接尝试使用状态,因为更新不一定会运行.相反,您可以使用第二个参数setState,这是一个回调:
this.setState({ myVal: 'newVal'},function() { // do something with new state });
这将在状态设置和组件重新呈现之后触发.