Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
React native 当抽屉屏幕在React Native中聚焦时,运行一些代码_React Native_React Navigation - Fatal编程技术网

React native 当抽屉屏幕在React Native中聚焦时,运行一些代码

React native 当抽屉屏幕在React Native中聚焦时,运行一些代码,react-native,react-navigation,React Native,React Navigation,因此,我创建了一个抽屉导航器: <NavigationContainer > <Drawer.Navigator initialRouteName="Home"> <Drawer.Screen name="Home" component={HomeScreen} /> <Drawer.Screen name="Account" component={Acc

因此,我创建了一个抽屉导航器:

 <NavigationContainer >
    <Drawer.Navigator  initialRouteName="Home">

      <Drawer.Screen  name="Home" component={HomeScreen} />
      <Drawer.Screen name="Account" component={AccountScreen} />
    </Drawer.Navigator>
  </NavigationContainer>

但它确实与组件Willmount一起工作。有什么方法可以检测用户何时进入该特定屏幕吗?

您可以在屏幕内使用
useFocusEffect
hook:

从'@react navigation/native'导入{useFocusEffect};
函数配置文件({userId}){
const[user,setUser]=React.useState(null);
聚焦效应(
React.useCallback(()=>{
const unsubscribe=API.subscribe(userId,user=>setUser(user));
return()=>unsubscribe();
},[userId])
);
返回;
}


如果您不能使用钩子,您可以收听焦点事件,但它没有太多的egronomic

您可以在屏幕内使用
useFocusEffect
钩子:

从'@react navigation/native'导入{useFocusEffect};
函数配置文件({userId}){
const[user,setUser]=React.useState(null);
聚焦效应(
React.useCallback(()=>{
const unsubscribe=API.subscribe(userId,user=>setUser(user));
return()=>unsubscribe();
},[userId])
);
返回;
}

如果不能使用钩子,则可以收听焦点事件,但这不是egronomoic

您可以订阅componentDidMount函数的内部,如下所示:

componentDidMount() {
    this.focusListener = navigation.addListener('focus', () => {
        // do something
    });
}
记住取消订阅inside componentWillUnmount

您可以按如下方式订阅inside-your componentDidMount功能:

componentDidMount() {
    this.focusListener = navigation.addListener('focus', () => {
        // do something
    });
}

记住取消订阅内部组件WillUnmount

你是一个genius@RodrigoSchroeder注意另一个答案。我的回答似乎有点过时了。建议使用useFocusEffect。我自己没有这方面的经验,但这可能值得一看。你是一个男人genius@RodrigoSchroeder注意另一个答案。我的回答似乎有点过时了。建议使用useFocusEffect。我自己没有这方面的经验,但可能值得一看。