当我想在屏幕打开时做一些动作时,我把它们放在componentDidMount中.例如,我可以获取一些数据.
像这样.
componentDidMount() { this.updateData(); }
但是反应导航componentDidMount只在用户第一次打开屏幕时出现一次,如果以后用户再次打开此页面则不会触发componentDidMount.
使用react-navigation,您可以做到这一点.
原文链接:https://www.f2er.com/react/300792.html>在componentDidMountor componentWillMount中添加侦听器
this.subs = [ this.props.navigation.addListener('didFocus',(payload) => this.componentDidFocus(payload)),];
要么
this.subs = [ this.props.navigation.addListener('didFocus',this.componentDidFocus),this.props.navigation.addListener('willBlur',this.componentWillBlur),];
然后你可以在componentDidFocus中做任何事情,比如获取数据,更新数据,……
>在componentWillUnmount中,删除侦听器
componentWillUnmount() { this.subs.forEach(sub => sub.remove()); }
有关更多详细信息,请参阅此PR:https://github.com/react-navigation/react-navigation/pull/3345
更新:
addListener
– Subscribe to updates to navigation lifecycleReact Navigation emits events to screen components that subscribe to
them:
willBlur
– the screen will be unfocused
willFocus
– the screen will focus
didFocus
– the screen focused (if there was a transition,the
transition completed)
didBlur
– the screen unfocused (if there was a transition,the
transition completed)
更新示例:
const didBlurSubscription = this.props.navigation.addListener( 'didBlur',payload => { console.debug('didBlur',payload); } );
JSON有效负载:
{ action: { type: 'Navigation/COMPLETE_TRANSITION',key: 'StackRouterRoot' },context: 'id-1518521010538-2:Navigation/COMPLETE_TRANSITION_Root',lastState: undefined,state: undefined,type: 'didBlur',};