簡體   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