我有如下数据。
this.state.jsonData = [
{
category: "1",
clientname: "rahul1",
reporthtml: "hello1"
},
{
category : "1",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
];
现在我需要在 React jsx 中渲染它,如下所示。无法使 if else 仅显示相同类别一次
我的html:
<div>
<div> Category Name</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
</div>
<div>
<div> Category Name</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
</div>
{this.state.jsonData.map(function(category,i) {
return <div> category.category</div>// This line will only print once for each category need if else condition
<div>Client Name</div>
<div>Client Html</div> ;
})}
最佳答案
如果我正确推断出您想要的内容,您只需使用嵌套的map
:
render() {
return <div>
{this.state.jsonData.map(function(category) {
return <div>
<div>Category: {category.category}</div>
{category.categorydata.map(function(data) {
return <div>
<div>Client: {data.clientname}</div>
<div>Report: {data.reporthtml}</div>
</div>;
})}
</div>;
})}
</div>;
}
实例:
class Category extends React.Component {
constructor(...args) {
super(...args);
this.state = {};
this.state.jsonData = [{
category: "1",
categorydata: [{
clientname: "rahul1",
reporthtml: "hello1"
}, {
clientname: "rahul2",
reporthtml: "hello2"
}, ]
}, {
category: "2",
categorydata: [{
clientname: "rahul1",
reporthtml: "hello1"
}, {
clientname: "rahul2",
reporthtml: "hello2"
}, ]
}];
}
render() {
return <div>
{this.state.jsonData.map(function(category) {
return <div>
<div>Category: {category.category}</div>
{category.categorydata.map(function(data) {
return <div>
<div>Client: {data.clientname}</div>
<div>Report: {data.reporthtml}</div>
</div>;
})}
</div>;
})}
</div>;
}
};
ReactDOM.render(
<Category />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
关于javascript - 使用 if else 条件在 React jsx 渲染函数内循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758643/