我是这样做的,但是现在我需要在调用函数之前保护文件的安全。当用户切换到屏幕时,我需要它立即被调用,因为将显示的项目来自提取。
useLayoutEffect(() => {
async function getUserData() {
var ingredients = await firebase.firestore().doc("ingredients/" + user.uid).get();
var labels = []
ingredients.data().ingredients.forEach(ingredient => {
labels.push(ingredient.label)
})
setUserIngredients(labels)
console.log(userIngredients)
setUserRecipes([])
}
getUserData()
fetchRecipes(userIngredients)
}, [])
这是fetchRecipes函数
function fetchRecipes(userIngredients) {
var number = 5
var url = "https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + userIngredients.join(",") + "&number=" + String(number) + "&apiKey=" + apiKey
fetch(url, {
method: "GET"
}).then((response) => response.json())
.then((responseJson) => {
for (var i = 0; i < number; i++) {
var newRecipe = {
id: responseJson[i].id,
title: responseJson[i].title,
image: responseJson[i].image,
ingredients: userIngredients
}
userRecipes.unshift(newRecipe)
}
firebase.firestore().doc("ingredients/" + user.uid).update({
recipes: userRecipes
})
console.log("Rezepte", userRecipes)
}).catch((error) => {
console.error(error);
})
}
答案 0 :(得分:0)
需要一些更改:
import React, { useState, useEffect } from 'react';
const useFetch = (targetUrl) => {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch(targetUrl);
const json = await response.json();
setData(json);
}
fetchData();
}, [targetUrl]);
return data;
};
const App = () => {
const URL = 'https://api.spoonacular.com/recipes/findByIngredients?ingredients=" + userIngredients.join(",") + "&number=" + String(number) + "&apiKey=" + apiKey';
const result = useFetch(URL);
return (
<div>
{JSON.stringify(result)}
</div>
);
}