Expo React Native 保持应用程序在**后台运行**

问题描述 投票:0回答:1

我有这段代码每 10 秒获取一次数据

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSecondsElapsed((prevSecondsElapsed) => prevSecondsElapsed + 1);
      if (secondsElapsed % 10 === 0) {
        // Every 10 seconds
        fetchData();
      }
    }, 1000);

    return () => clearInterval(intervalId);
  }, [secondsElapsed]);

和获取方法:

const fetchData = async () => {
    try {
      const data = await FetchData();
      setValue(data);

      const newLength = data.length;
      let hasNewItems = false;

      if (data && newLength > prevLengthRef.current) {
        console.log("New Order Received:", newLength - prevLengthRef.current,"new items added" );
        hasNewItems = true;
        sendNotification(expoPushToken); // Send notification

        setInitialLength(newLength);
        prevLengthRef.current = newLength;
      } else {
        console.log("No new orders received.");
      }
    } catch (error) {
      console.error("Error:", error.message);
      Alert.alert("Error", "Failed to fetch data. Please try again later.");
    }
  };

使用此解决方案,它无法在 Background 中工作,即使应用程序已关闭,如何设置应用程序在后台工作

react-native react-native-background-fetch react-notifications
1个回答
0
投票

要在后台获取,Expo 有一个跨平台 API

https://docs.expo.dev/versions/latest/sdk/background-fetch/

© www.soinside.com 2019 - 2024. All rights reserved.