React 迭代嵌套数组给出错误 Cannot read properties of null (reading 'value')
React iterating over nested array gives error Cannot read properties of null (reading 'value')
尝试映射嵌套数组时出现错误:数据结构如下:
错误:无法读取 null 的属性(读取 'value')
export const testData = [
{
"date": [
"2016-09-0912:00:00",
"2015-09-0913:10:00"
],
"title": [
{
"name": 'Name 1',
"description": [
{
"value": 7898
},
{
"value": 7898
}
]
},
{
"name": 'Name 2',
"description": [
{
"value": 3244
},
{
"value": 4343
}
]
},
{
"name": 'Name 3',
"description": [
null,
null
]
}
]
}
]
我试过:
<div style={{ color: 'white' }}>
Hello
{testData.map(inner => {
return (
<p style={{color: 'white'}}>{inner.title.map(inside => {
return (
inside.description.map(point => {
return (
point.value
)
})
)
})}</p>
)
})}
</div>
所以有点困惑?
这是因为 Name 3
对象的值为空。一个快速的解决方法是使用可选链接。
前
<div style={{ color: 'white' }}>
Hello
{testData.map(inner => {
return (
<p style={{color: 'white'}}>{inner.title.map(inside => {
return (
inside.description.map(point => {
return (
point?.value // here
)
})
)
})}</p>
)
})}
</div>
尝试映射嵌套数组时出现错误:数据结构如下:
错误:无法读取 null 的属性(读取 'value')
export const testData = [
{
"date": [
"2016-09-0912:00:00",
"2015-09-0913:10:00"
],
"title": [
{
"name": 'Name 1',
"description": [
{
"value": 7898
},
{
"value": 7898
}
]
},
{
"name": 'Name 2',
"description": [
{
"value": 3244
},
{
"value": 4343
}
]
},
{
"name": 'Name 3',
"description": [
null,
null
]
}
]
}
]
我试过:
<div style={{ color: 'white' }}>
Hello
{testData.map(inner => {
return (
<p style={{color: 'white'}}>{inner.title.map(inside => {
return (
inside.description.map(point => {
return (
point.value
)
})
)
})}</p>
)
})}
</div>
所以有点困惑?
这是因为 Name 3
对象的值为空。一个快速的解决方法是使用可选链接。
前
<div style={{ color: 'white' }}>
Hello
{testData.map(inner => {
return (
<p style={{color: 'white'}}>{inner.title.map(inside => {
return (
inside.description.map(point => {
return (
point?.value // here
)
})
)
})}</p>
)
})}
</div>