Javascript 如何迭代JS数组对象?无法读取属性';地图';未定义的
我犯了这个错误 未捕获的TypeError:无法读取未定义的属性“map” 当我尝试迭代对象数组时,如下所示。当IJavascript 如何迭代JS数组对象?无法读取属性';地图';未定义的,javascript,reactjs,Javascript,Reactjs,我犯了这个错误 未捕获的TypeError:无法读取未定义的属性“map” 当我尝试迭代对象数组时,如下所示。当Iconsole.log第一次迭代抛出空数组时,然后返回对象数组。我在映射对象数组之前进行了检查,如代码中所示。我错过什么了吗 ShipmentDetail.tsx export class ShipmentDetail extends Component<any, ShipmentInterface> { constructor(props: any) { s
console.log
第一次迭代抛出空数组时,然后返回对象数组。我在映射对象数组之前进行了检查,如代码中所示。我错过什么了吗
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;
状态中的细节是一个数组,它应该是一个对象。因此,在第一次渲染期间,空数组没有货物,因此它未定义,因此找不到贴图您将this.state.detail
设置为[]
,这是真实值,因此this.state.detail
返回true
,因此贴图
将在未定义时触发
解决方案是在constructor
中将detail
设置为null
编辑:您可以将其设置为任何假值,例如0
(零),“
空字符串,null
,undefined
,false
,NaN
,但我更喜欢null
此.state.detail
定义为数组(this.state={detail:[]/*…/}
)但它是作为对象访问的:this.state.detail.cargo
这就导致了错误,空数组没有cargo
属性,因此返回未定义的,您正试图在其上使用映射。
{
"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"
}
]
}