簡體   English   中英

在React組件中渲染JSON數組

[英]Rendering JSON array in React component

我正在嘗試顯示來自API的字符串數組。 但是我無法遍歷該數組。 如果我將整個數組傳遞到HTML標簽內,則它將呈現為字符串。

例如: <div>{data.list.ingredients}</div>正在工作並顯示為字符串。 如果我嘗試管理此data.list.ingredients[0]它將引發錯誤:

Cannot find 0 of undefined

我的數組:

{
  "_id": "5b5446df2c89ab3d0e8d5526",
  "title": "Chicken with Mustard Cream Sauce",
  "vegetarian": false,
  "ingredients": [
    "4 whole Boneless Skinless Chicken Breasts",
    "2 Tablespoons Olive Oil",
    "2 Tablespoons Butter",
    "3 whole Garlic Cloves Minced",
    "1 cup Brandy",
    "1 Tablespoon (heaping) Dijon Mustard",
    "1 Tablespoon (heaping) Grainy Mustard",
    "1/4 cup (to 1/2) Heavy Cream",
    "1/4 cup (to 1/2) Chicken Broth",
    "Salt And Pepper"
  ],
  "image_url": "http://static.food2fork.com/chickenmustarde587.jpg",
  "steps": [
    "Amount of cream and broth has slightly decreased add more as needed",
    "Cut the chicken breasts in half lengthwise so that you have eight smaller thinner chicken cutlets Salt and pepper both sides",
    "Heat oil and butter in a large skillet over mediumhigh heat Cook cutlets on both sides until nice and golden brown and cooked through Remove chicken from the skillet and keep on a plate",
    "Reduce the heat to medium Add the garlic to the pan and saute it for a minute stirring to make sure it wont burn Next pour in the brandy or wine if using being careful if cooking over an open flame Then just let the booze bubble up and cook until its reduced by half",
    "Throw in the mustards and stir to combine then pour in the cream Stir in chicken broth adding more if the sauce seems too thick Taste sauce and adjust whatever you think it needs Add chicken breasts back to the pan nestling them into the sauce Allow sauce to cook for another few minutes shaking the pan if needed to move things around",
    "Serve chicken with a green salad spooning the sauce over the top"
  ],
  "serving": 5,
  "cooking_time": 20
}
function renderData(){
  let array = ['a','b','c','d' ];
  return array.map((item, index) => <div key={index}>{ item }</div>);
}

我假設您正在使用axios(API組件),因此在您的情況下,您可以獲得以下結果:

axios.get('/youringredients.json')
  .then(res => {
  const ingredient = res.data.list.ingredients[0];
  console.log(ingredient);
});

您也可以在您的狀態下使用成分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM