简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'map') in react

I get this error, when I try to run my code:

TypeError: Cannot read properties of undefined (reading 'map')

Here is my code:

import React, { Component } from "react";
import _ from "lodash";

class TableBody extends React.Component {
  render() {
    const { data, columns } = this.props;
    return (
      <tbody>
        {data.map((item) => (
          <tr>
            {columns.map((column) => (
              <td>{_.get(item, column.path)}</td>
            ))}
          </tr>
        ))}
      </tbody>
    );
  }
}

export default TableBody;

if data is something that comes from a remote request it is undefined at the first render, until a response comes. Or maybe you are doing some computation in the parent component in which data is undefined when the component gets render. You can write you code like this:

const { data = [], columns = [] } = this.props;

Which set the values to an empty array if they are undefined.

However be sure that you are passing an array and not something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM