首页 > 解决方案 > Expo React Native 进入视图时执行函数

问题描述

我试图在视图处于前台时执行一个函数,但不是在每次更新组件时执行一次。如果用户导航到另一个视图并返回到第一个视图,它应该再次执行该功能,但只执行一次。有针对这个的解决方法吗?

如果使用不带第二个参数的 useEffect 它会在每次更新时执行,如果我添加 [] 作为第二个参数,它只会在第一次呈现视图时执行,但在导航回视图时不会执行。任何帮助表示赞赏!

标签: react-nativereact-hooksexpouse-effect

解决方案


如果您使用的是react-navigation,您可以通过在屏幕焦点上收听来做到这一点,请参见此处

  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // The screen is focused
      // Call any action
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

推荐阅读