我知道我可以在我的
extendedIngredients
接口中更改Recipe
以返回string[]
,以便它与API调用数据的结果匹配并解决错误,但问题是当我更改时
extendedIngredients: [
{
original: string;
}
];
到
extendedIngredients: string[];
我得到了
'original' does not exist on type 'string'
的问题。但我需要这个才能从我的 API 调用中获取特定于路径的数据。
useEffect(() => {
const getRecipe = async () => {
try {
const res = await fetch(
`https://api.spoonacular.com/recipes/${id}/information?apiKey=KEY&includeNutrition=false`
);
const data = await res.json();
recipeInfo(data);
// console.log(data);
} catch (err) {
console.error(err);
}
};
getRecipe();
}, [id]);
const recipeInfo = (info: Recipe) => {
const recipeData: Recipe = {
id: info.id,
title: info.title,
image: info.image,
servings: info.servings,
readyInMinutes: info.readyInMinutes,
dairyFree: info.dairyFree,
glutenFree: info.glutenFree,
ketogenic: info.ketogenic,
vegan: info.vegan,
vegetarian: info.vegetarian,
extendedIngredients: info.extendedIngredients.map((ing) => ing.original),
};
console.log(recipeData);
};
我对打字稿很陌生,我显然不明白一些东西,有什么帮助吗?
不清楚是什么或在哪里产生了您提到的第二个错误,因此不清楚您是否“真的”需要使用仅具有一个属性的对象数组而不是字符串数组。但是... 如果您只需要它返回一组仅具有一个属性的对象:
info.extendedIngredients.map((ing) => ing.original)
然后您将从
.map()
回调中返回该对象:
info.extendedIngredients.map((ing) => ({ original: ing.original }))