简体   繁体   English

屏幕切换时的反应导航调用功能

[英]React-navigation call function on screen change

I need to acquire data from the server to load user set settings when the user changes screen. 当用户更改屏幕时,我需要从服务器获取数据以加载用户设置。 It is done by a function in the class. 它由类中的函数完成。 I have tried: 我努力了:

componentWillMount(){
  console.log("Sent to function");
  this.onSaveCats('initialize');
}

What does not post anything to console log. 什么不向控制台日志发布任何内容。 I have not found a good solution for triggering a function when a new screen is changed. 在更改新屏幕时,我没有找到触发功能的好方法。 Is there something I am missing? 我有什么想念的吗?

  "dependencies": {
    "expo": "^20.0.0",
    "react": "16.0.0-alpha.12",
    "react-native": "^0.47.0",
    "react-native-radio-buttons": "^1.0.0",
    "react-navigation": "^1.0.0-beta.11"
  }

In react navigation, we can subscribe to listeners and add corresponding callbacks. 在反应导航中,我们可以订阅侦听器并添加相应的回调。 The four events that we can subscribe to listeners on are: willFocus, willBlur, didFocus and didBlur. 我们可以订阅的四个事件是:willFocus,willBlur,didFocus和didBlur。

Usage in this case: 在这种情况下的用法:

    export default class AnyScreen extends Component{
     constructor(props){
       super(props);
       const didBlurSubscription = this.props.navigation.addListener(
       'didBlur',
       payload => {
             console.debug('didBlur', payload);
       });
      }
    }

You can add similar subscription for didFocus as well by substituting 'didBlur' to any of the other options. 您也可以通过将“ didBlur”替换为其他任何选项来为didFocus添加类似的订阅。

Once you're done listening, you can even remove the listener subscription: 侦听完成后,甚至可以删除侦听器订阅:

didBlurSubscription.remove();

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM