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

May*_*oni 2 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,
    }
}
Run Code Online (Sandbox Code Playgroud)

先感谢您。

den*_*emm 5

React 导航有自己的导航生命周期 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)
Run Code Online (Sandbox Code Playgroud)