我得到一个数组,其中包含另一个数组。它是一个 json。我正在尝试执行两个循环,但没有成功。
{this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) =>
{alarms.report && alarms.report.forEach((alarm) =>
<ReportAlarmRow alarm={alarms} alarmType={alarm}/>
)}
)}
我尝试从 forEach 开始,然后再进行 .maps。再次失败。
最佳答案
为了便于阅读,您应该在 return
之前执行这些循环声明。
此外,还需要添加key
属性(property)给您<ReportAlarmRow>
组件。
A "key" is a special string attribute you need to include when creating lists of elements.
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Lists and Keys - React documentation
我用 key={alarm[i].id}
设置了 key 但我不知道你的alarm
中有哪些属性对象。
请使用唯一的int值!
Keys Must Only Be Unique Among Siblings
尝试这样
constructor(props) {
super(props);
// State
this.state = {
listOfAlarms: []
}
}
render() {
const reports = this.state.listOfAlarms.map((alarms) => {
if (alarms.report) {
return alarms.report.map((alarm) =>
<ReportAlarmRow alarm={alarms} alarmType={alarm} key={alarm.id} />
);
}
});
return {
<div>
{ reports.length ? reports : null }
</div>
}
}
关于javascript - 如何在React JS中设置两个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631122/