在React本机中从另一个函数内部调用函数

lhcgjxsq  于 2023-01-05  发布在  React
关注(0)|答案(1)|浏览(143)

我想从HelloWorldApp函数内部调用snapShotTaker函数,但是在终端得到ERROR TypeError: undefined is not a function, js engine: hermes,这个问题怎么解决?

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);
  };
ifmq2ha2

ifmq2ha21#

你不能在组件外部调用它,但是你可以使用useEffect hook把notifee代码移到你的组件内部并在那里调用它。

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.
  });

相关问题