在屏幕之间导航但构造函数未调用

时间:2019-01-04 13:03:53

标签: react-native react-navigation

我的应用程序中有多个屏幕,我使用CreatStackNavigator进行导航。 如果我第二次访问屏幕,则不会调用构造函数。

假设我有四个屏幕A,B,C和D,目前我在A。

然后我分别转到C屏幕和D屏幕。

现在,如果我再次单击C,则不会调用C的构造函数。

我也使用了ComponentReceivedMount(),但是没有用。

我的代码是:-

  constructor(props) {
    super(props);
    ToastAndroid.show('heeeelll', ToastAndroid.LONG);
    this.state = {
        drawerOpen: false,
        op: 1,
        cl: '#ffffff',
        swiper: this.renderSwpier,
        showSwiper: false,
        ftc: '#2c3554',
        stc: '#c8c8c8',
        firstTopcolor: 1,
        secondTopColor: 0,
        showview: true,
    }
}

谢谢。

2 个答案:

答案 0 :(得分:0)

第二次调用C不会调用构造函数,因为在u从A调用它之前,已经安装了C,并且在生成类的新实例时调用构造函数。 您可以使用componentwillmount()和componentdidmount()代替依赖于构造方法的方法。

答案 1 :(得分:0)

反应导航具有其自己的导航生命周期API,该API可让您确定屏幕何时处于活动状态。

有关更多信息,请检查文档:https://reactnavigation.org/docs/en/navigation-lifecycle.html

withNavigationFocus HOC提供了isFocused道具,可让您确定屏幕是否可见。

示例:

import { withNavigationFocus } from 'react-navigation';

class YourScreen extends React.Component {

  render() {
     ...
  }

  componentDidUpdate(prevProps) {
    if (this.props.isFocused && !prevProps.isFocused) {
      // Screen has now come into focus, perform your tasks here! 
    }
  }

}

export default withNavigationFocus(YourScreen)
相关问题