React:如何将数据渲染到组件中?

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 中,因此它不会起作用,您需要 return 父 map 函数的值:

{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;