简体   繁体   中英

How to fetch data an array instead of an object in JS?

So im not 100% sure that this is the problem, but Im using the fetch method to grab data from this link https://swapi.py4e.com/api/people . And then im trying to use the .map function on it. Instead of working, I get a Unhandled Rejection (TypeError): jedis.map is not a function error.

When I console logged jedis I got everything you see in that link, like count: 87, next: " https://swapi.py4e.com/api/people/?page=2 ", etc.

Im assuming that the error means that jedis is actually a object and not an array. But again, im not totally sure thats the reason. If it is, how can I access the data so that jedis is an array and not an object

import React from 'react';
import './App.css';
import CardList from './CardList'

class App extends React.Component{
  constructor() {
    super();
    this.state = {
      jedis: []
    }
  }

  componentDidMount() {
    fetch('https://swapi.py4e.com/api/people').then(resp => resp.json())
    .then(jedi => this.setState({jedis: jedi}));
  }


  render() {
    return (
      <CardList jedis={this.state.jedis}/>

      )
  }

}

export default App;
import React from 'react'
import Card from './Card'

const CardList = ({ jedis }) => {
    return (
        <div>
            {
                //console.log(jedis)
                jedis.map((jedi, i) => {
                    return (
                        <Card
                            key = {i}
                            name = {jedi.name}
                            height = {jedi.height}
                            mass = {jedi.mass}
                        />
                        )

                })

            } 
        </div>

    )   


}


export default CardList;

Heres the API im using incase anyone is wondering http://swapi.py4e.com/

Based on the response of the API,

Change your CardList component props to:

<CardList jedis={this.state.jedis.results} />

Also, then you need to change your state initialisation to:

this.state = {
  jedis: {
    count: 0,
    previous: null,
    next: null,
    results: []
  }
}

Assuming you want to keep adding to the array on every fetch, you will want to use the spread operator and previousState .

fetch('https://swapi.py4e.com/api/people').then(resp => resp.json())
.then(jedi => { 

    this.setState((previousState) => {
      return {
        jedis: [...previousState.jedis, jedi.results],
      };
    });

});

It's quite simple. Actually you need to convert the response object to Array and you will be good to run map on it. Below is an example assume you get numbers as keys, if your obj response keys are not numbers but regular strings you can replace Number(key) with key in return statement.

var obj = { "1": 5, "2": 7, "3": 0, "4": 0}; var result = Object.keys(obj).map(function (key) { return [Number(key), obj[key]]; });

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