简体   繁体   中英

TypeError: Cannot read property 'map' of undefined React.js

I am trying to parse data from my Web API and show it on my react page, the connection is successful and the data is parsed (I can see an array of elements in the console) but whenever I want to show it on the page I get this error:

TypeError: Cannot read property 'map' of undefined.

I am using axios for the connection so here is my code:

import React from 'react';
import axios from 'axios';

class Player extends React.Component {
    state = {
      loading: true,
      error: "",
      data: []
  };  

  loadData = () => {
    this.setState({ loading: true });
    return axios
      .get('http://localhost:6444/api/example')
      .then(result => {
        console.log(result);
        this.setState({
          data: result.data.items,
          loading: false,
          error: false
        });
      })
      .catch(error => {
        console.error("error: ", error);
        this.setState({
          error: `${error}`,
          loading: false
        });
      });
  };

  componentDidMount() {
      this.loadData();
    }

    render() {
      const { loading, error, data } = this.state;
      if (loading) {
        return <p>Loading ...</p>;
      }
      if (error) {
        return (
          <p>
            There was an error loading the players.{" "}
            <button onClick={this.loadData}>Try again</button>
          </p>
        );
      }
      return (
        <div>
          <h1>Players</h1>
          <p>{data.map((player, index) => {
            return (
              <div key={index} player={player}></div>
            )})}</p>
        </div>
      );
    }   
}

export default Player;

I hope anyone can help me figure out the problem, I tried many things by now but nothing fixed the problem.

Based on your comment including the output of result , you should change your state update to:

this.setState({
  data: result.data,
  loading: false,
  error: false
});

Your data items must be directly on data, not under a key of data.items .

There's no items property inside results.data. This should be enough.

this.setState({
  data: result.data,
  loading: false,
  error: false
});

Change the render for your div to put content inside the div

<p>{data.map((player, index) => {
  return (
    <div key={index}>{player}</div>
)})}</p>

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