我正在尝试映射一些看起来像这样的json数据...
"array": [
{
"controlPanel": "00000000-0000-0000-0000-000000000000",
"lastArmed": "2016-10-31T19:36:19.3943138",
"lastDisarmed": "2017-02-04T22:50:47.3528838",
"panelDateTime": "2019-10-14T09:00:31.0908467",
"mainsConnected": false,
"mainsLastActivated": "2017-04-19T04:53:47.9033877",
"tamperStatus": "0",
"activeFaults": "TwoW, AC, BP, DF, LV, NF, OP, SR",
"battery": {
"voltage": 0.0,
"current": 0
},
"system": {
"voltage": 6.515163,
"current": 1547
},
"aux12V": {
"voltage": 2.767401,
"current": 119
},
"bell": {
"voltage": 14.019639,
"current": 405
},
"network": null,
"temperature": 68.538864,
"id": "fd14f8da-2175-e75d-e2a2-00647f9d3884"
},
我不断收到TypeError:这样做时无法读取未定义的属性“ map” ...
{this.state.controlPanelStatus.battery.map((b, bix) => (
<tr key={bix}>
<th>Battery Voltage (V)</th>
<td>{b.voltage}</td>
<td>Pass</td>
<td>10.5V<>14.5V</td>
</tr>
))}
我的状态是这样定义的...
class ControlPanelDetail extends React.Component {
constructor(props) {
super(props);
this.timeIncrementMs = 50;
this.showSpinnerIfReturnGreaterThanMs = 200;
this.state = {
loading: false,
controlPanel: [],
controlPanelStatus: [
{
"battery": {
"voltage": '',
"current": ''
},
"system": {
"voltage": '',
"current": ''
},
"aux12V": {
"voltage": '',
"current": ''
},
"bell": {
"voltage": '',
"current": ''
},
}
],
toggledClearRows: false
}
}
我只是这样从api加载第一个条目...
fetch('/api/controlpanelstatus')
.then(res => res.json())
.then(cp => {
this.setState({
controlPanelStatus: cp.array[0],
isLoading: false
});
console.log(this.state.controlPanelStatus)
})
.catch(error => {
if (error.response) {
console.log(error.responderEnd);
}
});
所有数据均从我试图映射的嵌套json中正确加载。 我在这里做错了什么?是因为json未嵌套为数组,例如[]? 谢谢。
答案 0 :(得分:2)
我在.map()
函数中更改了您的代码。我所做的只是在运行时处理异常。
{
this.state.controlPanelStatus &&
this.state.controlPanelStatus.map((b, bix) => (
<div key={bix}>
// ...
</div>
));
}