当屏幕出现时调用哪个生命周期事件?

Which lifecycle event is called when a screen appears?

假设我有两个屏幕:

我最初登陆 屏幕 A。当我单击 Button 时,我导航到 屏幕 B。当我按 Back Button 时,我再次导航到 屏幕 A

我想在导航到上述场景中提到的屏幕 A 时调用动作创建器。

我只想知道每次显示屏幕时会调用哪个生命周期事件。

有没有像componentWillAppear()这样的活动?

注意:我正在使用 react-nativereact-navigation 进行导航。

当您从一个屏幕导航到另一个屏幕时,第一个屏幕不会被卸载,但仍在堆栈中,只是隐藏在后台。

您需要的可能是 componentDidFocus,但它目前处于设计阶段,尚不可用,请参阅 react-native open issue #51

您可以试试这个替代方法:react-navigation-addons。有了这个,您可以举办活动 focus & blur,这可能适合您的需要。

如果你使用react-native-navigation,你可以监听外观事件:https://wix.github.io/react-native-navigation/#/screen-api?id=listen-to-visibility-events-globally

这现在可以通过他们的听众通过简单的反应导航来完成:

在您的组件 A 中:

componentDidMount = () => {
  this._componentFocused();

  this._sub = this.props.navigation.addListener(
    'didFocus',
    this._componentFocused
  );
}

componentWillUnmount() {
  this._sub.remove();
}

_componentFocused = () => {
  this.setState({dataToShow});
}

React Navigation docs - Lifecycle