我如何从API获取数据(当我使用map时,我得到TypeError:userdata.map不是一个函数)

时间:2020-02-24 10:30:53

标签: reactjs api axios

我需要帮助来显示API中的数据。 当我尝试使用地图获取数据时,出现错误。 TypeError:userdata.map不是函数

import React from "react";
import axios from "axios";
export class HighscoreList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: ""
    };
  }
  componentDidMount() {
    axios
      .get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <React.Fragment>
        <h2>User</h2>
        {this.state.users}
      </React.Fragment>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

尝试这个https://codesandbox.io/s/wonderful-cherry-63ee9

export default class HighscoreList extends React.Component {
    state = {
      users: []
    };

  componentDidMount() {
      axios
      .get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
      .then(res => this.setState({users:[res.data]}))
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    const {users} = this.state;
    let array = users[0]?Object.values(users[0]):[];
    console.log(array)
    return (
      <React.Fragment>
         {array.map((arr,index)=>
          <div key={index}>
          <h2>{arr.username}</h2>
          <p>{arr.email}</p>
          </div>
          )}
      </React.Fragment>
    );
  }
}