react实现map循环嵌套渲染问题
日期:2019-02-09
来源:程序思维浏览:5422次
查了一些资料貌似react的循环渲染对象只有map,但map只支持数组对象。
接到后台数据如下
{
"list": {
"A": [{
"image": "http:///b1.jpg",
"name": "奥迪",
"id": "1"
}],
"B": [{
"image": "http:///b1.jpg",
"name": "奔驰",
"id": "1"
}]
}
}
需要循环拿到A、B再循环拿到 A、B里边的数据
异步拿到数据后处理如下:
getbrandInfoFun = async type => {
try {
let result = await API.getbrandInfo({
id: 'wechat'
});
let carListArr = [];
for (let item in result.list) {//async、await中不支持map foreach 所以只能for方法
let reobj = {};
reobj[item] = result.list[item];
carListArr.push(reobj);
}
this.setState({
brandInfoList: carListArr,/* 正面状态 */
});
} catch (err) {
}
}
render处理如下:
<div className="carbrand_listbox">
{
this.state.brandInfoList.map((value, index) => {
let carListArr=[];
let carListkey=[];
for (let item in value) {
carListkey=item
carListArr=value[item];
}
return (
<div key={index}>
<div className="weui-cells__title" id="" >{carListkey}</div>
{
carListArr.map((item, numberN) => (
<div key={numberN} className="weui-cell" data-carbrandid="" >
<div className="weui-cell__hd">
<img className="lazy" src={item.image} />
</div>
<div className="weui-cell__bd">
<p >{item.name}}</p>
</div>
</div>
))
}
</div>
)
})
}
</div>
实现效果:
接到后台数据如下
{
"list": {
"A": [{
"image": "http:///b1.jpg",
"name": "奥迪",
"id": "1"
}],
"B": [{
"image": "http:///b1.jpg",
"name": "奔驰",
"id": "1"
}]
}
}
需要循环拿到A、B再循环拿到 A、B里边的数据
异步拿到数据后处理如下:
getbrandInfoFun = async type => {
try {
let result = await API.getbrandInfo({
id: 'wechat'
});
let carListArr = [];
for (let item in result.list) {//async、await中不支持map foreach 所以只能for方法
let reobj = {};
reobj[item] = result.list[item];
carListArr.push(reobj);
}
this.setState({
brandInfoList: carListArr,/* 正面状态 */
});
} catch (err) {
}
}
render处理如下:
<div className="carbrand_listbox">
{
this.state.brandInfoList.map((value, index) => {
let carListArr=[];
let carListkey=[];
for (let item in value) {
carListkey=item
carListArr=value[item];
}
return (
<div key={index}>
<div className="weui-cells__title" id="" >{carListkey}</div>
{
carListArr.map((item, numberN) => (
<div key={numberN} className="weui-cell" data-carbrandid="" >
<div className="weui-cell__hd">
<img className="lazy" src={item.image} />
</div>
<div className="weui-cell__bd">
<p >{item.name}}</p>
</div>
</div>
))
}
</div>
)
})
}
</div>
实现效果:
精品好课