使用React从API正确获取数据

I am using an API which contains cards. And to call this API, I am using Axios. So far so good, but I want to return the deck_id and for some reason it does not work. And I get the error "this.state.card.map is not a function"

这是我当前的代码:

import React from "react";
import axios from "axios";
const CARD_API = "https://deckofcardsapi.com/api/deck/new/shuffle/";

export default class PersonList extends React.Component {
  constructor(props) {
     super(props)
     this.state = {
       card: []
     }
  }

  async componentDidMount() {
     const card= await axios.get(CARD_API)
     this.setState({ card})
  }

  render() {
     return (
        <ul>
           {this.state.card.map(card=>
              <li>{card.deck_id}</li>
           )}
        </ul>
     )
  }
}
评论
  • et_qui
    et_qui 回复

    In axios you will get data inside response.data , so this is how you will get access to data

    try {
    
        const response = await axios.get(MOVIE_API); //<-- This will have a lot more thing apart from data you need
        const movie = response.data; //<---- SOLUTION
        this.setState({ movie })
    
    } catch (err) {
        console.log(err)
    }
    

    Note : Always put your async await code within try catch block if possible