gpt4 book ai didi

javascript - 使用 if else 条件在 React jsx 渲染函数内循环

转载 作者:行者123 更新时间:2023-12-03 05:12:11 26 4
gpt4 key购买 nike

我有如下数据。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com