繁体   English   中英

我对对象数组使用了 map 方法,但是这个数组中的一个项目也是对象数组所以我需要获取它的属性

[英]I used map method for array of objects items but one item inside this array is also array of object So I need to take its properties

这是在反应应用程序中 src 内的共享文件夹中

export const DISHES =  [
        {
        id: 0,
        name:'sss',
        image: 'assets/images/ssss.png',
        category: 'dddd',
        comments: [
            {
            id: 0,
            rating: 5,
            comment: "dddd",
            author: "ddd",
            date: "3353"
            }
    ]

这是在 App.js 中

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dishes: DISHES,
    };
  }
  
  render() {
    return (
      <div className="App">
        <Navbar dark color="primary">
          <div className="container">
            <NavbarBrand href="/">Ristorante Con Fusion</NavbarBrand>
          </div>
        </Navbar>
        <Menu dishes={this.state.dishes}/>
      </div>
    );
  }
}

和这个来自 menuComponent.js 的渲染方法

render() {
    const menu = this.props.dishes.map((dish) => {
      return (
        <div className="col-12 col-md-6 my-1">
          <Card key={dish.id} onClick={() => this.onDishSelect(dish)}>
            <CardImg width="100%" src={dish.image} alt={dish.name} />
            <CardImgOverlay>
              <CardTitle>{dish.name}</CardTitle>
            </CardImgOverlay>
      {/* <p>{dish.map(dish => <div>{dish.comments}</p> */}
          </Card>
        </div>
      );
    });
    return (
      <div className="container">
        <div className="row">{menu}</div>
        <div className="row">{this.renderDish(this.state.selectedDish)}</div>
      </div>
    );

  }

现在,我需要使用具有对象数组的 comments 属性,而他自己是我之前在渲染方法中使用的地图项之一

要映射内部数组,您只需要正确访问属性。 dish comments属性,以及comments数组中每个元素的comment属性,为了简洁起见,可以进行对象解构。

dish.comments.map(({ comment }) => <div>{comment}</div>)

代码:

render() {
    const menu = this.props.dishes.map((dish) => {
      return (
        <div className="col-12 col-md-6 my-1">
          <Card key={dish.id} onClick={() => this.onDishSelect(dish)}>
            <CardImg width="100%" src={dish.image} alt={dish.name} />
            <CardImgOverlay>
              <CardTitle>{dish.name}</CardTitle>
            </CardImgOverlay>
            <p>
              {dish.comments.map(({ comment }) => <div>{comment}</div>)}
            </p>
          </Card>
        </div>
      );
    });
    return (
      <div className="container">
        <div className="row">{menu}</div>
        <div className="row">{this.renderDish(this.state.selectedDish)}</div>
      </div>
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM