我有一个React本机应用程序,其中我正在使用React Navigation V3。我想在按特定标签栏上创建一个事件。在我的家庭标签栏上,我有条形码扫描仪。当用户扫描时,该应用将带有条形码数据将数据设置为异步存储的其他选项卡。但是当我尝试再次扫描时,它会变为空白。
因此,我想创建一个事件,当用户转到Home Tab再次扫描时,我可以在其上清除异步存储。如何在家庭选项卡栏中添加该活动?
尝试以下代码,它将为您提供帮助,
import {NavigationEvents} from "react-navigation";
<NavigationEvents
onWillFocus={payload => console.log('will focus',payload)}
onDidFocus={payload => console.log('did focus',payload)}
onWillBlur={payload => console.log('will blur',payload)}
onDidBlur={payload => console.log('did blur',payload)}
/>
NavigationEvents
组件您可以在要跟踪用户事件的页面渲染方法中添加,并像AsyncStorage
一样处理和您想要的任何操作。
仅当您不需要全部时添加一个事件
有关更多详细信息,您可以在此处访问
谢谢
您可以侦听导航生命周期事件。
设置相当直接。这是如何在屏幕中设置它的示例。
import React, {Component} from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default class Screen2 extends React.Component {
// willFocus - the screen will focus
// didFocus - the screen focused (if there was a transition, the transition completed)
// willBlur - the screen will be unfocused
// didBlur - the screen unfocused (if there was a transition, the transition completed)
componentDidMount () {
// add listener
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.willFocusAction);
this.didFocusSubscription = this.props.navigation.addListener('didFocus', this.didFocusAction);
this.willBlurSubscription = this.props.navigation.addListener('willBlur', this.willBlurAction);
this.didBlurSubscription = this.props.navigation.addListener('didBlur', this.didBlurAction);
}
componentWillUmount () {
// remove listener
this.willFocusSubscription.remove()
this.didFocusSubscription.remove();
this.willBlurSubscription.remove();
this.didBlurSubscription.remove();
}
willBlurAction = () => {
console.log('willBlur Screen', new Date().getTime())
}
didBlurAction = () => {
console.log('didBlur Screen', new Date().getTime());
}
didFocusAction = () => {
console.log('didFocus Screen', new Date().getTime());
}
willFocusAction = () => {
console.log('willFocus Screen', new Date().getTime());
}
render() {
return (
<View style={styles.container}>
<Text>Screen</Text>
</View>
)
}
}
您不需要添加所有听众,而只需添加所需的听众。您很可能需要从willFocus
事件中的AsyncStorage
中清除您的值。这样,它发生在屏幕焦点之前。