问题
您的初始状态没有提供足够的数据结构,无法更深入地正确访问。
这个
beers
对象最初在中定义为空数组
Home
this.state = {
beers: [],
}
并作为道具传递给
TileList
<TileList beerList={this.state.beers} /> // this.state.beers ~ []
内
TileList
你试图立即更深入地记录
console.log(props.beerList.children[0]);
检查这一点,
props.beerList
当前是空数组(
[]
)没有财产
children
,即。
props.beerList.children
或
props.beerList['children']
未定义,因此尝试访问索引
0
将抛出错误
Uncaught TypeError: Cannot read property '0' of undefined
.
次要问题
初始状态为
beers = []
,但稍后响应形状是一个对象
{
name: 'Products', attributes:{}, value:'', children: [
{
name:'Beers', attributes: {}, value: '', children: [
{
name: 'Product', attributes:{}, value:'', children: {
}
}
]
}
]
}
这种不一致的状态类型会使调试代码变得更加困难,或者换句话说,更容易产生有缺陷的代码。
解决方案
保持状态类型一致。
this.state = {
beers: {},
}
首先使用防护装置或可选的链条进行检查
props.beerList.children &&
props.beerList.children.length &&
console.log(props.beerList.children[0]);
或
console.log(props.beerList?.children?.[0]);
访问正确的嵌套属性以映射啤酒
props.beerList.children &&
props.beerList.children.length &&
props.beerList.children[0].children &&
props.beerList.children[0].children.map(product => ...