【问题标题】:While coming back from react navigation componentWillMount doesn't get called从反应导航返回时,不会调用 componentWillMount
【发布时间】:2017-09-18 12:52:53
【问题描述】:

我使用了 react-navigation 并在 android 中单击硬件后退按钮时,我回到了前一个组件,但没有调用 componentWillMount。如何确保 componentWillMount 被调用?

【问题讨论】:

标签: react-native-android react-navigation


【解决方案1】:

componentWillMount 不会在你进入新屏幕/返回屏幕时触发。

我的解决方案是使用事件导航器处理程序 https://wix.github.io/react-native-navigation/#/screen-api?id=listen-visibility-events-in-onnavigatorevent-handler

您可以在触发“willAppear”事件 id 时实现“componentWillMount”代码,请参阅此实现:

export default class ExampleScreen extends Component {
  constructor(props) {
    super(props);
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
  }
  onNavigatorEvent(event) {
    switch(event.id) {
      case '`willAppear`':
       // { implement your code on componentWillMount }
       break;
      case 'didAppear':
        break;
      case 'willDisappear':
        break;
      case 'didDisappear':
        break;
      case 'willCommitPreview':
        break;
    }
  }
}

【讨论】:

【解决方案2】:

@bumbur 的这个回答对你有帮助吗?它定义了一个全局变量,用于跟踪导航状态是否已更改。您可以插入一段代码来查看您是否在您感兴趣的特定选项卡中。这样您就可以触发对 componentWillMount() 的调用?

如果你不想使用 redux,这就是你可以全局存储的方式 有关当前路线的信息,因此您可以同时检测选项卡更改 并告诉哪个选项卡现在处于活动状态。

https://stackoverflow.com/a/44027538/7388644

export default () => <MyTabNav
    ref={(ref) => { this.nav = ref; }}
    onNavigationStateChange={(prevState, currentState) => {
         const getCurrentRouteName = (navigationState) => {
         if (!navigationState) return null;
         const route = navigationState.routes[navigationState.index];
         if (route.routes) return getCurrentRouteName(route);
         return route.routeName;
    };
    global.currentRoute = getCurrentRouteName(currentState);
  }}
/>;

【讨论】:

    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 2022-01-25
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多