[英]React: how to render data into a component?
我想將數據從 props 傳遞到另一個組件,但我在從嵌套數組傳遞數據時遇到問題。 我的 JSON 具有以下結構:
[
{
id: 1,
category: "Fish",
nodes: [
{
id: 1,
title: "Bacalhau com broa",
ingredients: [
"bacalhau",
"broa"
]
},
{
id: 2,
title: "Bacalhau à Zé do Pipo",
ingredients: [
"bacalhau",
"broa",
"5 cebolas"
]
},
],
}
];
我嘗試了以下方法,其中dishesData
包含來自JSON 的nodes
:
{dishesData.map((dishes) => {
dishes.forEach((dish) => {
console.log(dish.title)
return <Dish title={dish.title} ingredients={dish.ingredients} />;
});
})}
console.log(dish.title)
正在正確打印但未將我的組件呈現到頁面。
您的 return 語句在forEach
內,因此它不起作用,您需要將值返回給父map
function:
{dishesData.map((dishes) => {
return dishes.map((dish) => {
return <Dish title={dish.title} ingredients={dish.ingredients} />;
});
})}
import React from 'react';
// Json data
const dishesData = [
{
id: 1,
category: "Fish",
nodes: [
{
id: 1,
title: "Bacalhau com broa",
ingredients: [
"bacalhau",
"broa"
]
},
{
id: 2,
title: "Bacalhau à Zé do Pipo",
ingredients: [
"bacalhau",
"broa",
"5 cebolas"
]
},
],
}
];
// First component - I have used a functional component
const ComponentOne = (props) => {
// output: Bacalhau com broa, Bacalhau à Zé do Pipo
const answer = dishesData.map(dishes => {
dishes.nodes.map(dish=> dish.title)
});
// a title prop is pased to ComponentTwo component
return (
<ComponentTwo title = {answer} />
);
}
// Another component that will receive our props passed to it
const ComponentTwo = (props) => {
console.log(props.title)
return (
<p> {props.title} </p>
)
}
export default ComponentOne;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.