【问题标题】:React JS - Error Cannot read property 'map' of undefined when rendering a TableReact JS - 渲染表格时出错无法读取未定义的属性“地图”
【发布时间】:2018-12-06 11:05:32
【问题描述】:

我正在尝试使用 ReactJS 呈现表格,但收到错误 - 无法读取未定义的属性 'map' -

代码:

import React, { Component } from 'react';
import './Table.css'

const obj = [{
    name: "onion",
    price: ".99",
    id: 1
}, {
    name: "pepper",
    price: "1.25",
    id: 2
}, {
    name: "broccoli",
    price: "3.00",
    id: 3
}];

class TableRow extends React.Component {
    render() {
        const {
            data
        } = this.props;
        const row = data.map((data) =>
            <tr>
                <td key={data.name}>{data.name}</td>
                <td key={data.id}>{data.id}</td>
                <td key={data.price}>{data.price}</td>
            </tr>
        );
        return (
            <span>{row}</span>
        );
    }
}

class Table extends Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <table>
                <TableRow data={this.props.data} />
            </table>
        );
    }
}

export default Table;

我将表格组件导入到 App.js 文件中。但是,错误发生在 Table.js 的以下行: const row = data.map((data) => ......我可以得到一些帮助吗?

【问题讨论】:

  • 能否也分享一下 App.js,以便我们查看您作为道具传递给
    组件的数据类型?
  • 您的data 似乎是undefined。您确定您在渲染时获取数据吗?
  • 你在哪里给Table它的data道具?那是data 一个数组吗?顺便说一句,data.map((data) =&gt; ---) 是错误的,不能在同一个作用域内定义 2 个同名变量
  • const obj = ...data 一样吗?

标签: javascript reactjs


【解决方案1】:

您很可能不会将数组作为data 传递给Table

Table 组件应该在 App.js 或者你使用它的地方设置,如下所示:

class App extends Component {
  render() {
    return (
      <div className="App">
        <Table data={[1,5,6,etc. . .]} /> \\data has an array of whatever values you care for.
      </div>
    );
  }
}

之后你还会遇到另一个问题,因为你不应该在TableRow 中设置data = this.propsdata 应设置为 this.props.data,如下所示:

const {
        data
    } = this.props.data;

【讨论】:

    【解决方案2】:

    在您的 table 类中,将以下代码从 &lt;TableRow data={this.props.data} /&gt; 更改为 &lt;TableRow data={obj} /&gt;

    您定义了obj,但您从未在任何地方使用它。当程序渲染您的table 类并尝试渲染TableRow 时,它使用data 属性传递数据。但是您在没有数据的情况下使用 this.props.data 传递,因此当 TableRow 尝试应用 map 函数时,它会遇到异常

    【讨论】:

    • 谢谢,编辑解决了我遇到的问题;也感谢您的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2021-01-06
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    相关资源
    最近更新 更多