我有一个复杂的场景,我真的很困惑如何处理它。 我有一个数组如下:
stories=[
{
"categ": "politics",
"arr": [{
"t": 1
}, {
"t": 2
}, {
"t": 3
}]
},
{
"categ": "Business",
"arr": [{
"t": 1
}, {
"t": 2
}, {
"t": 3
}]
}
]
正如您所看到的,该数组内部有另一个数组,根据执行的内容,我需要循环第一个数组并在第一个数组内找到适当的数组。因此,例如,如果我想获取与业务类别相关的数组,我需要循环第一个数组并选择与业务相关的数组。为此,我有以下代码:
<div className="row">
{
this.props.stories.map((item,i)=> <Story key={i} position={i} story={item} ></Story>)
}
</div>
所以你可以看到,使用map我可以循环遍历第一个数组。现在考虑通过使用 this.props.categ 我可以访问我想要的类别。所以我必须将我的代码更改为如下所示:
<div className="row" >
{
this.props.stories.map(function(snippet){
if(snippet.categ==="politics"){
return(
snippet.arr.map((item,i)=> <Story key={i} position={i} story={item} ></Story>)
);
}
})
}
</div>
但是在上面的代码中,“politics”是硬编码的,应该用 this.props.categ 替换。但是,一旦我更换它,我就会收到错误消息
Uncaught TypeError: Cannot read property 'props' of undefined
这完全有道理,因为我失去了父级,因为我不使用 es6 fat arrow。现在如何才能做到这一点?
最佳答案
您可以像这样绑定(bind)外部 map 函数
<div className="row" >
{
this.props.stories.map(function(snippet){
if(snippet.categ===this.props.categ){
return(
{snippet.arr.map((item,i)=> <Story key={i} position={i} story={item} ></Story>})
);
}
}.bind(this))
}
</div>
这将允许您的映射函数引用 prop
可用的外部上下文。此外,您还忘记将内部 map 函数包含在 {}
其他选项是使用箭头功能
<div className="row" >
{
this.props.stories.map(snippet) => {
if(snippet.categ===this.props.categ){
return(
{snippet.arr.map((item,i)=> <Story key={i} position={i} story={item} ></Story>})
);
}
}.bind(this))
}
</div>
关于javascript - 当我有两个内部循环时无法获取此属性的父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41541822/