简体   繁体   中英

How to iterate reactjs array object ? Cannot read property 'map' of undefined

I'm getting this error

Uncaught TypeError: Cannot read property 'map' of undefined

when I try iterate array of object as below. When I console.log first iteration throwing empty array and after that return array of object. I did checking before map array of object as in code. Did I miss anything?

ShipmentDetail.tsx

export class ShipmentDetail extends Component<any, ShipmentInterface> {
  constructor(props: any) {
    super(props);

    this.state = {
      detail: [] as any[]
    };
  }

  componentDidMount() {
    this.getShipmentDetail();
  }

  getShipmentDetail() {
    let { params } = this.props.match;
    params = params.id;
    axios
      .get(`http://localhost:3001/shipments/${params}`)
      .then((response: any) => {
        this.setState({ detail: response.data });
      });
  }
  render() {
    return (
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>type</TableCell>
            <TableCell>description</TableCell>
            <TableCell>volume</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {this.state.detail &&
            this.state.detail.cargo.map((row: any) => {
              <TableRow>
                <TableCell component="th" scope="row">
                  wewe
                </TableCell>
                <TableCell>{row.description}</TableCell>
                <TableCell>{row.volume}</TableCell>
              </TableRow>;
            })}
        </TableBody>
      </Table>
    );
  }
}

export default ShipmentDetail;

Here is sample response from http://localhost:3001/shipments/${params}

Sample.json

{
  "id": "S1000",
  "name": "T-shirts(Summer2018) from Shanghai to Hamburg",
  "cargo": [
    {
      "type": "Fabric",
      "description": "1000 Blue T-shirts",
      "volume": "2"
    },
    {
      "type": "Fabric",
      "description": "2000 Green T-shirts",
      "volume": "3"
    }
  ],
  "mode": "sea",
  "type": "FCL",
  "destination": "Saarbrücker Str. 38, 10405 Berlin",
  "origin": "Shanghai Port",
  "services": [
    {
      "type": "customs"
    }
  ]
}

You set this.state.detail to [] which is truthy value, so this.state.detail returns true , so map will fire on undefined

Solution is to set detail to null in constructor

EDIT: you can set it to any falsey value such as 0 (zero), "" empty string, null , undefined , false , NaN but I'd prefer null

Detail in your state is an array, it should be an object. So during the first render empty array does not have cargo, so it is undefined and thus map is not found

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