React Native:如何在一段时间后提取,比如24小时



我想在24小时后获取,这样用户就可以从应用程序中获得新的食谱。现在我在屏幕渲染时调用它,但我希望它在一定时间后提取,例如24小时,我需要一个函数,即使在应用程序关闭时也能计算时间。有办法做到这一点吗?

async function getUserData() {
var userData = await firebase.firestore().doc("ingredients/" + user.uid).get();
var labels = []
userData.data().ingredients.forEach(ingredient => {
labels.push(ingredient.label)
})
userData.data()
setUserIngredients(labels)
fetchRecipes(labels)
}

function fetchRecipes(userIngredients) {
var url = "https://europe-west3-cookingapp-b71aa.cloudfunctions.net/fetchRecipes?userIngredients=" + userIngredients.join('+') + "&idToken=" + user.idToken
fetch(url, {
method: "GET"
}).then((response) => response.json())
.then((responseJson) => {
responseJson = JSON.parse(responseJson)
if (responseJson) {
var newRecipes = []
for (var i = 0; i < 3; i++) {
const hit = responseJson.hits[Math.floor(Math.random() * responseJson.hits.length)]
const newRecipe = {
id: hit.recipe.uri,
image: hit.recipe.image,
label: hit.recipe.label,
time: hit.recipe.totalTime,
}
newRecipes.unshift(newRecipe)
}
setIsLoading(false);
setUserRecipes(newRecipes)
}
else {
console.log("Fehler")
}
})
}

这是我现在的功能

check react本机后台获取:https://github.com/transistorsoft/react-native-background-fetch

我的建议是使用AsyncStorage将当前获取执行的时间节省到存储中。然后,当你的应用程序启动时,检查存储值并计算差异时间。如果符合您的条件,则重新执行调用函数。

最新更新