[
0: {_id: '61de38eb6ea1563609e1d0a7', title: 'FALCON SR SUNTOUR', price: '59', description: ' Alloy.., …}
1: {_id: '61d7a8b885c68311be8dd1b3', title: 'Lifelong LLBC2702 Falcon', price: '59', description: 'Low Maintenance: High.., …}
]
我正在創建一個反應專案。我的資料庫中有上述物件陣列。如果任何用戶下訂單,訂單串列和用戶電子郵件將進入單個陣列。所以我的問題是如何顯示訂單。我嘗試了一個地圖,也嘗試了一個嵌套地圖,但得到了“order.map 不是函式”。這是代碼
{orders.map((order, idx) => order.map(singleOrder => console.log(singleOrder)))}
我想將訂單詳細資訊分解為 UI
這是我的代碼:
const ManageAllOrders = () => {
const [orders, setOrders] = useState([])
const { user } = UseAuth()
useEffect(() => {
fetch(`https://polar-savannah-40370.herokuapp.com/dashboard/orders`)
.then(res => res.json())
.then(data => setOrders(data))
}, [user.email])
console.log('orders', orders);
return (
<div>
<h2>Manage Orders</h2>
<Table responsive striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Price</th>
<th>Email</th>
<th>Address</th>
<th>Order Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{
orders?.map((order, idx) =>
Object.defineProperties(order).map(([key, value]) => {
return (
<div>
{key} : {value}
</div>
);
})
)}
{/* {orders.map((order, idx) => order[0].map(console.log()))} */}
</tbody>
</Table>
</div>
);
};
export default ManageAllOrders;
uj5u.com熱心網友回復:
您不能呼叫map每個訂單專案,因為它是一個object. 迭代它們使用Object.entries方法。
嘗試如下
{
orders?.map((order, idx) =>
Object.entries(order).map(
([key, { description, title, price, cartQuantity }]) => {
if (key !== "_id") {
return (
<tr>
<td>{key}</td>
<td>{title}</td>
<td>{price}</td>
<td>{cartQuantity}</td>
<td>{description}</td>
<td>email</td>
<td>address</td>
</tr>
);
}
}
)
);
}
我還注意到您的陣列存盤了帶有字串鍵(email,_id)的值。要檢索它們,您可以像下面那樣進行操作。
{orders?.["email"]}
{orders?.["_id"]}
代碼沙箱
uj5u.com熱心網友回復:
資料型別是陣列嗎??
useEffect(() => {
fetch(`https://polar-savannah-40370.herokuapp.com/dashboard/orders`)
.then(res => res.json())
.then(data => setOrders(data))
}, [user.email])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417442.html
標籤:
上一篇:在JavaScript中使用Object.assign()從具有重復鍵的物件陣列中創建具有不同結構的多個物件陣列
