简体   繁体   中英

Call a function from inside of another function in React Native

I want to call snapShotTaker function from inside of HelloWorldApp function but i get ERROR TypeError: undefined is not a function, js engine: hermes in terminal. How to solve this problem?

notifee.registerForegroundService(notification => {
  return new Promise(() => {
    // Long running task...
    setInterval(() => {
      HelloWorldApp.snapShotTaker();
    }, 2000);
  });
});

const HelloWorldApp = () => {
  const isAppForeground = useIsForeground();
  console.log('In Foreground?: ', isAppForeground);

  const cameraRef = useRef(null);
  const [finalPath, setPhotoPath] = useState('');

  const devices = useCameraDevices();
  const device = devices.front;

  if (device == null) {
    return <ActivityIndicator style={styles.indicator} size="large" />;
  }

  const snapShotTaker = async () => {
    const snapshot = await cameraRef.current.takeSnapshot({
      quality: 20,
      skipMetadata: true,
    });
    setPhotoPath('file://' + snapshot.path);
  };

You simply can't call it outside of the component. However you can move the notifee code to inside of your component using the useEffect hook and call it there.

const HelloWorldApp = () => {
  const isAppForeground = useIsForeground();
  console.log('In Foreground?: ', isAppForeground);

  const cameraRef = useRef(null);
  const [finalPath, setPhotoPath] = useState('');

  const devices = useCameraDevices();
  const device = devices.front;

  if (device == null) {
    return <ActivityIndicator style={styles.indicator} size="large" />;
  }

  const snapShotTaker = async () => {
    const snapshot = await cameraRef.current.takeSnapshot({
      quality: 20,
      skipMetadata: true,
    });
    setPhotoPath('file://' + snapshot.path);
  };

  useEffect(() => {
    // Register your service
    notifee.registerForegroundService(notification => {
      return new Promise(() => {
        // Long running task...
        setInterval(() => {
         snapShotTaker();
        }, 2000);
      });
    });

    // You need to stop the service on cleanup, so it doesn't register multiple times.
    // See https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
    return () => {
      notifee.stopForegroundService();
    };
  
  // You can pass the snapShotTaker function to the deps array but it won't affect it since it isn't memoized. See useCallback hook if you want to memoize it.
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM