javascript - 当我有两个内部循环时无法获取此属性的父属性

标签 javascript reactjs

我有一个复杂的场景,我真的很困惑如何处理它。 我有一个数组如下:

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/

相关文章:

javascript - 启用代码 View 时无法调用 editor.insertText

javascript - 批量编辑复杂文本文件

javascript - 无法将原型(prototype)函数编写为 JavaScript 中的函数声明。为什么?

javascript - React 无法在 axios 之外分配类字段

reactjs - Jest/Enzyme document.createRange 不是挂载函数

javascript - React 在重新渲染父组件时如何重用子组件/保持子组件的状态?

reactjs - 为什么我会收到此错误 - 未找到错误 : EPERM: operation not permitted, mkdir 'C:\Users\Aniket' 命令:create-react-app

javascript - 粘性导航栏

javascript - 将第一个元素保存到待办事项数组中时出现问题

javascript - 是否可以将 Dojo 与其他 JS 框架结合起来?