英文:
accessing and displaying arrays of objects via api with react.ts
问题
我正在尝试使用React.ts从食谱API中显示步骤/配料列表,但不确定如何定义嵌套对象数组的类型。
我能够访问标题、图像和摘要,但无法访问analizedInstructions
中的步骤。
以下是我的类型文件:
export type RecipeData = {
title: string,
analizedInstructions: Steps[],
image: string,
summary: string
}
export type Steps = {
steps: Name[]
}
export type Name = {
name: string
}
这是我从API获取的数据,我试图访问的数据:
英文:
i am trying to display list of steps/ingredients from the recipe api with react.ts but i am unsure how to define the type of nested array of objects.
i am able to access the title, image and summary but not the steps in analizedInstructions.
export function RecipeDetails() {
const initialRecipeState = {
title: '',
analizedInstructions: [{
steps: [{
name: ''
}]
}],
image: '',
summary: ''
}
const { id } = useParams();
const [data, setData] = useState<RecipeData>(initialRecipeState);
useEffect( () => {
const getData = async() => {
const newData = await fetchData(`https://api.spoonacular.com/recipes/${id}/information?apiKey=key&includeNutrition=false`)
setData(newData)
}
getData();
console.log(data.analizedInstructions)
},[])
this is my types file
export type RecipeData = {
title: string,
analizedInstructions: Steps,
image: string,
summary: string
}
export type Steps = {
name: Name
}
export type Name = {
name: string
}
and this is the data i get from the api im tying to access
api data
i tried to find a solution via stackoverflow but didnt find quite what i was looking for.
答案1
得分: 0
export type RecipeData = {
title: string,
analizedInstructions: Instruction[],
image: string,
summary: string
}
export type Instruction = {
steps: Step[]
}
export type Step = {
name: string
}
英文:
export type RecipeData = {
title: string,
analizedInstructions: Instruction[],
image: string,
summary: string
}
export type Instruction = {
steps: Step[]
}
export type Step = {
name: string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论