【发布时间】:2020-05-05 19:08:31
【问题描述】:
在我的 React Native 应用程序中,我有一个想要在出现特定屏幕时触发的事件。我将事件放在componentDidMount 中,因此它会在屏幕首次加载时触发,但如果我离开屏幕并向左滑动返回屏幕,则屏幕已经安装,因此不会触发事件。
我应该如何处理这个问题?
【问题讨论】:
标签: javascript reactjs react-native
在我的 React Native 应用程序中,我有一个想要在出现特定屏幕时触发的事件。我将事件放在componentDidMount 中,因此它会在屏幕首次加载时触发,但如果我离开屏幕并向左滑动返回屏幕,则屏幕已经安装,因此不会触发事件。
我应该如何处理这个问题?
【问题讨论】:
标签: javascript reactjs react-native
如果您使用react-navigation,您可以在componentDidMount 中执行此操作以在已安装的屏幕上触发事件。
componentDidMount() {
const {navigation} = this.props;
this.onFocusTrigger = navigation.addListener('focus', () => {
// trigger your event
});
}
除了'focus',你还可以根据需要使用following。
willFocusdidFocusdidBlurwillBlur你需要像这样在componentWillUnmount中取消订阅监听器
componentWillUnmount() {
this.onFocusTrigger();
}
【讨论】:
这取决于您的导航框架。例如,如果你使用 React Navigation,你应该查看Navigation Events。 (确保您使用的文档版本与您正在使用的版本相符。)
【讨论】: