【问题标题】:Interact over object of arrays React JS在数组对象上交互 React JS
【发布时间】:2021-09-30 20:21:17
【问题描述】:

我有一个像这样的对象:

[
    {
        "periodname": "Test",
        "periodtime": ""
    },
    {
        "periodname": "",
        "periodtime": ""
    }
]

我想为其中的每个数组呈现一个 Col。我的反应代码:

function renderMyPage(props) {

const { myObject } = props

const renderMyPage = () => {
     return [myObject].map((c,i) => {
        return(
            <Col>
              My data here  
            </Col>
          )
       })
    }
}

但我总是只得到一个结果,即使我的对象中有两个或多个数组。

如果我再次与 ma​​pforeach 交互,我会得到相同的对象。 如果我在对象上使用 map 函数而不使用“[]”,则会出现错误:

Uncaught TypeError: Cannot read property 'map' of undefined

我做错了什么只得到一个结果?围绕 StackOverflow 问题尝试了很多其他问题,但我得到了相同的结果。

【问题讨论】:

    标签: javascript arrays reactjs object


    【解决方案1】:

    作为一个快速解决方案尝试

    const renderMyPage = () => {
         return myObject?.map((c,i) => {
            return(
                <Col>
                  My data here  
                </Col>
              )
           })
        }
    }
    

    const renderMyPage = () => {
         if (!myObject) return null;
        
         return myObject.map((c,i) => {
            return(
                <Col>
                  My data here  
                </Col>
              )
           })
        }
    }
    

    【讨论】:

    • 如果你想告诉 TypeScript 编译器你确定 myObject 被定义,你可以使用 return myObject!.map(...
    猜你喜欢
    • 2021-07-07
    • 2022-01-21
    • 2022-10-12
    • 2022-09-29
    • 1970-01-01
    • 2013-05-10
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多