[英]How to iterate reactjs array object ? Cannot read property 'map' of undefined
I'm getting this error我收到这个错误
Uncaught TypeError: Cannot read property 'map' of undefined
未捕获的类型错误:无法读取未定义的属性“地图”
when I try iterate array of object as below.当我尝试如下迭代对象数组时。 When I
console.log
first iteration throwing empty array and after that return array of object.当我
console.log
第一次迭代时抛出空数组,然后返回对象数组。 I did checking before map
array of object as in code.我在
map
对象数组之前做了检查,就像在代码中一样。 Did I miss anything?我错过了什么吗?
ShipmentDetail.tsx ShipmentDetail.tsx
export class ShipmentDetail extends Component<any, ShipmentInterface> {
constructor(props: any) {
super(props);
this.state = {
detail: [] as any[]
};
}
componentDidMount() {
this.getShipmentDetail();
}
getShipmentDetail() {
let { params } = this.props.match;
params = params.id;
axios
.get(`http://localhost:3001/shipments/${params}`)
.then((response: any) => {
this.setState({ detail: response.data });
});
}
render() {
return (
<Table>
<TableHead>
<TableRow>
<TableCell>type</TableCell>
<TableCell>description</TableCell>
<TableCell>volume</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.detail &&
this.state.detail.cargo.map((row: any) => {
<TableRow>
<TableCell component="th" scope="row">
wewe
</TableCell>
<TableCell>{row.description}</TableCell>
<TableCell>{row.volume}</TableCell>
</TableRow>;
})}
</TableBody>
</Table>
);
}
}
export default ShipmentDetail;
Here is sample response from http://localhost:3001/shipments/${params}
这是来自
http://localhost:3001/shipments/${params}
示例响应
Sample.json示例.json
{
"id": "S1000",
"name": "T-shirts(Summer2018) from Shanghai to Hamburg",
"cargo": [
{
"type": "Fabric",
"description": "1000 Blue T-shirts",
"volume": "2"
},
{
"type": "Fabric",
"description": "2000 Green T-shirts",
"volume": "3"
}
],
"mode": "sea",
"type": "FCL",
"destination": "Saarbrücker Str. 38, 10405 Berlin",
"origin": "Shanghai Port",
"services": [
{
"type": "customs"
}
]
}
You set this.state.detail
to []
which is truthy value, so this.state.detail
returns true
, so map
will fire on undefined
您将
this.state.detail
设置为[]
这是真实值,因此this.state.detail
返回true
,因此map
将在undefined
时触发
Solution is to set detail
to null
in constructor
解决方案是在
constructor
中将detail
设置为null
EDIT: you can set it to any falsey value such as 0
(zero), ""
empty string, null
, undefined
, false
, NaN
but I'd prefer null
编辑:您可以将其设置为任何假值,例如
0
(零)、 ""
空字符串、 null
、 undefined
、 false
、 NaN
但我更喜欢null
Detail in your state is an array, it should be an object.您状态中的细节是一个数组,它应该是一个对象。 So during the first render empty array does not have cargo, so it is undefined and thus map is not found
所以在第一次渲染时空数组没有货物,所以它是未定义的,因此找不到地图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.