【问题标题】:React mapping object key of the array to display as table's head failed反应数组的映射对象键以显示为表头失败
【发布时间】:2021-05-05 04:10:25
【问题描述】:

我试图让数组的对象键显示为表的标题,但在反应中使用映射失败。 通过使用 console.log,我能够看到它返回正确的值,它在 HTML 上返回空白。

这是我的代码

<tr>
{fileList.forEach((titleList) => {
      const title = [];
       title.push(Object.keys(titleList))
        // console.log(title) 
       title.map((item, key) => {
         // console.log(item)
           return <th key={key} scope="col">{item}</th>
        })
    })
}
</tr>

json 数据来自这里:https://jsonplaceholder.typicode.com/posts/1/comments 如果您愿意检查,这是我的完整项目代码:https://codesandbox.io/s/dry-wave-gu0ns?file=/src/listPage/ListPage.js

谢谢!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您在 forEach 中所做的任何事情都不会转到您的 JSX,即使您在 forEach 内的 map 内返回。

    要么将整个代码移动到另一个函数,要么尝试以下方法

    <tr>
    {fileList.map((titleList) => {
          const titles = Object.keys(titleList);
            // console.log(title) 
           return titles.map((item, key) => {
             // console.log(item)
               return <th key={key} scope="col">{item}</th>
            })
        })
    }
    </tr>
    

    这样从fileList.map返回的内容会显示在页面中。

    另一种使用函数的方法

    function getHeaders(fileList) {
    let headers = [];
    
    fileList.forEach((titleList) => {
          const title = [];
           title.push(Object.keys(titleList))
            // console.log(title) 
           const head = title.map((item, key) => {
             // console.log(item)
               return <th key={key} scope="col">{item}</th>
            })
            headers = headers.concat(head);
        })
      }
      return headers;
    }
    

    在你的 jsx 中使用这个

    <tr>
       {getHeaders(fileList)}
    </tr>
    

    【讨论】:

    • 非常感谢您的解释:D
    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 2015-05-16
    • 2020-07-29
    • 2020-10-31
    • 1970-01-01
    • 2019-01-07
    • 2020-06-01
    • 2020-08-20
    相关资源
    最近更新 更多