【问题标题】:React: Creating a row per item in an array [duplicate]反应:在数组中为每个项目创建一行[重复]
【发布时间】:2018-07-25 01:02:15
【问题描述】:

我将一个对象数组作为道具传递给我的 Table 组件,它应该将数组中的每个项目转换为表中的一行。但它没有输出任何东西......

我已经使用console.log 成功查看了数组中的每个项目。这是我的代码:

import React from 'react'; 

export default class Table extends React.Component {
    getTableRow(x) {
        console.log(x); 
        return ( <tr>
                <td>{x.prop1}</td>
                <td>{x.prop2}</td>
                <td>{x.prop3}</td>
        </tr>); 
    }

    resolveInput() {
        //expecting array
        const array = this.props.lastFiveList; 
        //array.map(x => console.log(x)); 
        array.map(x => this.getTableRow(x)); 
    }           

    render() {
        return (
            <table>
             {this.resolveInput()}
            </table>
        ); 
    }
}

我还尝试绑定这两个函数(结果相同)并将 getTableRow 应该返回的内容放入变量中,然后返回变量而不是多行 return(); 语句。此外,我尝试使用forEach 而不是map

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    您的 resolveInput() 方法没有返回您从地图创建的数组,也没有返回任何与此相关的内容。 因此,请尝试从传入的数组中返回您映射的新数组。

    【讨论】:

      【解决方案2】:

      resolveInput 方法没有返回任何东西。你需要返回

      resolveInput() {
          //expecting array
          const array = this.props.lastFiveList; 
          //array.map(x => console.log(x)); 
          return  array.map(x => this.getTableRow(x)); 
      
      
      } 
      

      【讨论】:

      • @GabyakaG.Petrioli 感谢您的指点。我更新了错误。
      【解决方案3】:

      你没有返回resolveInput()中的数组:

          return array.map(x => this.getTableRow(x));
      

      【讨论】:

      • 我需要有关该组件的更多信息来帮助您。 this.props.lastFiveList 来自哪里?
      • 没关系,我解决了。你是对的......我的 resolveInput 没有返回任何东西。谢谢你,米格尔!我认为您的回复最先出现,因此请在几分钟内将您的回答视为已接受的答案。
      • @user8951490 另请注意,您将收到有关trs 不是tbody 元素的子元素的警告,并且您的trs 需要密钥。 Here's a fixed version.
      猜你喜欢
      • 2021-09-30
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多