简体   繁体   中英

Displaying JSON data using Fetch API and map() in Javascript/Reactjs

I have been trying to grab json data from an API and display it using the map() function. Unfortunately the API returns data in the format: { "type": ..., "value": ... }. The second object value contains an array with the data I want to access.

Is there a way I can access (or single out) JUST the second object in the API? and then I can run map() on it. See code below. This currently returns the error: this.state.jokes.map is not a function

PS the code works pefectly on APIs wrapped in an array eg http://jsonplaceholder.typicode.com/posts

class JokeList extends React.Component {

    constructor() {
        super();
        this.state = {jokes:[]};

    }

    componentDidMount() {
        fetch(`http://api.icndb.com/jokes`)
            .then(result => result.json())
            .then(jokes => this.setState({jokes}))
    }

    render () {

        return (
            <div> 
                {this.state.jokes.map(joke => 
                       <div key={joke.id}> {joke.joke} </div>)}
            </div>
        );
    }
}

Try using

fetch(`http://api.icndb.com/jokes`)
    .then(result => result.json())
    .then(jokes => this.setState({jokes: jokes.value}))

instead.

This is because the response from the API is like this:

{
  "type": "...",
  "value": [the value you want],
}

You want the value of the value key, because that's what you're using later.

class JokeList extends React.Component {

    constructor() {
        super();
        this.state = {jokes:[]};

    }

    componentDidMount() {
        fetch(`http://api.icndb.com/jokes`)
            .then(result => result.json())
            .then(jokes => this.setState({jokes}))
    }

    render () {

        return (
            <div> 
                {this.state.jokes.map(joke => 
                       <div key={joke.id}> {joke.joke} </div>)}
            </div>
        );
    }
}

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