我正在使用地图渲染一个列表op产品在我的应用程序。如下所示:
<div className={`content ${isLoading ? 'is-loading' : ''}`}>
<div className="panel">
{!isLoading && orders.length > 0
? orders.map((order, index) => {
const { productname, image, quantity, orderid, category } = order;
return (
<div className="product" key={orderid}>
<div className="plaatjediv" onClick={this.toggleModal.bind(this)}>
<img
className="img-responsive"
data-itemIndex={index}
src={image}
/>
</div>
<div className="productInfo">
<p>{productname}</p>
<p>Aantal: {quantity}</p>
</div>
<div className="bdone">
<button
className="btn btn-lg btn-default btndone"
data-itemIndex={index}
onClick={this.handleDoneAction}
>
Done
</button>
</div>
</div>
);
})
: null}
</div>
</div>;
状态命令包含以下代码:
fetch('http://localhost:54408/api/orders/all/testing-9!8-7!6/' + todayy)
.then(response => response.json())
.then(parsedJSON =>
parsedJSON.map(product => ({
productname: `${product.ProductName}`,
image: `${product.Image}`,
quantity: `${product.Quantity}`,
category: `${product.Category}`,
orderid: `${product.OrderId}`,
}))
)
.then(orders =>
this.setState({
orders,
isLoading: false,
})
)
.catch(error => console.log('parsing failed', error));
现在,我想按类别将产品分组并输出如下:
- <h3>category 1</h3>
- image - productname - quantity
- image - productname - quantity
- <h3>category 2</h3>
- image - productname - quantity
- image - productname - quantity
以此类推
我不知道如何将我的产品按类别分组,并以类别名称作为每个产品组的标题,按类别显示它们。我希望有人能进一步帮助我。
更新
我设法将数组分组为
但我不能用地图或其他东西来渲染。
类别名称现在是数字,但这可能会在以后出现。
发布于 2018-05-03 07:10:54
您的第一步是使用类似在JavaScript对象数组上,最有效的组群方法是什么?或lodash的方法对数据进行分组。
然后,您的数据将类似于:
const data = [{
category: 'category1',
orders: [
{productname: 'pn1', image: 'img1', quantity: 1, orderid: 'ord1'},
{productname: 'pn2', image: 'img2', quantity: 2, orderid: 'ord2'}
]
}, {
category: 'category2',
orders: [
{productname: 'pn3', image: 'img3', quantity: 1, orderid: 'ord3'},
{productname: 'pn4', image: 'img4', quantity: 2, orderid: 'ord4'},
{productname: 'pn5', image: 'img5', quantity: 2, orderid: 'ord4'},
]
}];
然后,可以在呈现方法中使用两个嵌套的.map
:
render() {
return Object.keys(data).map(cat => (
<div>
<h3>{cat}</h3>
{data[cat].map(ord => (
<div>
<div>{ord.productname}</div>
<div>{ord.image}</div>
<div>{ord.quantity}</div>
<div>{ord.orderid}</div>
</div>
))}
</div>
))
}
发布于 2018-05-03 07:12:01
在呈现数据之前,可以按categoryId对数据进行分组。
groupBy = (data, key) {
return data.reduce(function(acc, item) {
(acc[item[key]] = acc[item[key]] || []).push(item);
return acc;
}, {});
};
renderData() {
const data = this.groupBy(this.state.orders, 'category');
return Object.keys(data).map(objKey => <React.Fragment key={objKey}>{
<h3>{objKey}</h3>
{data[objKey].map(order => <ul>
<li>{order.image}</li>
<li>{order.Quantity}</li>
<li>{order.ProductName}</li>
</ul>) }
}</React.Fragment>)
}
render() {
<div>{this.renderData()}</div>
}
https://stackoverflow.com/questions/50148658
复制相似问题