通过 React.ts 使用 API 访问和显示对象数组。

huangapple go评论61阅读模式
英文:

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获取的数据,我试图访问的数据:

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
}

huangapple
  • 本文由 发表于 2023年2月18日 03:53:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定