React组件中呈现JSON数组



我正在尝试显示来自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);
});

你也可以在你的状态下使用这种成分。

最新更新