[英]How do I iterate through an Array of Objects and display each objects into a Chart?
[英]How do I map an through an array of objects and display each object individually? I want each pizza order to show
我不確定如何遍歷每個訂單並將它們顯示為單獨的訂單。 api 響應看起來像這樣......
0:
地殼:“薄”
口味:“奶酪”
訂單 ID:2
尺寸:“S”
表_編號:5
時間戳:“2019-12-03T18:21:08.708470”
並且可以繼續獲得盡可能多的訂單。 我不需要 Order_ID 顯示,所以也許這是一種迭代方式?
import React, { Component } from 'react'
import axios from 'axios';
export default class Orders extends Component {
constructor() {
super();
this.state = {
order: "no orders yet",
crust: "no crust selected",
// flavor: "no flavor selected",
// size: "no size selected",
// table: "place an order first",
// timestamp: "place an order first"
};
}
handleButtonClick = () => {
axios.get("/orders").then(response => {
this.setState({
orders: response,
crust: response.data[0].Crust
// flavor: response.data[0].Flavor
//etc..
});
})
}
render() {
return(
<div>
<button onClick={this.handleButtonClick}></button>
<h1>orders are:</h1>
<p>Crust: {this.state.crust}</p>
</div>
);
}
}
export { Orders }
由於您的狀態中有 orders 數組,因此您需要在模板上對其進行迭代,使用地圖,然后呈現每個訂單所需的元素。
而不是僅僅從狀態渲染地殼,你會做這樣的事情:
{this.state.orders.map((order) => (
<p>Crust: {order.crust}</p>
))}
我很快創建 了一個示例 CodeSandbox 來執行此操作。
從我從你的代碼塊中可以看出,這應該有效。 只需將訂單數組設置為 response.data,然后在渲染函數中遍歷訂單數組。
constructor() {
super();
this.state = {
orders: []
};
}
handleButtonClick = () => {
axios.get("/orders").then(response => {
this.setState({
orders: response.data
});
})
}
render() {
const orderData = this.state.orders.map(order => {
return })
return(
<div>
<button onClick={this.handleButtonClick}></button>
<h1>orders are:</h1>
{this.state.orders.map((order) => (
<p>Flavor: {order.flavor}</p>
<p>Crust: {order.crust}</p>
))}
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.