无法在 React js 中使用 console.log 打印属性

Not able to print properties with console.log in React js

我想打印从父组件 GroceryList

传递到我的组件 GroceryListItem 的 Props

我的 GroceryList 代码:

    class GroceryList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          groceries: [ { name: "Apples"}, {name: "Orange"}, {name : "Banana"} ]
        };
      }

    render() {
        const element = [];
        for(var index = 0; index < this.state.groceries.length; index++) {
           element.push(<ul><GroceryListItem grocery={this.state.groceries[index]} /></ul>);
        }

        return (
         <div>
           {element}
         </div>
    );
  }
}

我的 GroceryListItem 代码:

class GroceryListItem extends React.Component {

 constructor(props) {
    super(props);

  }

render() {
    // I want to print the props passed here, but below code is not printing it
    console.log("Hi from GroceryListItem " + this.props.grocery); 

    return (
        <li>
          {this.props.grocery}
        </li>
    );
  }
}

控制台打印:

Hi from GroceryListItem [object Object]

控制台显示 [object Object] 但不是像 Apples, Orange, Banana 这样的精确值。如何打印 props

中的所有值

您需要访问对象的 name 属性

class GroceryListItem extends React.Component {

 constructor(props) {
    super(props);

  }

render() {
    console.log("Hi from GroceryListItem " + this.props.grocery.name); 
    return (
        <li>
          {this.props.grocery.name}
        </li>
    );
  }
}