简体   繁体   中英

React doesn't render API data

Im building a recipe App and I got stuck and there is no error display or anything that can help me, Its my first time working with APIS in React and Im a little bit lost thats why im asking.

I´m trying to fetch data from this API and I don´t know why the properties will not show on the screen since I ve another example where it does.

I can see in the console with the React Developer extension that the properties are passed to the state so that´s fine and I dont understand why I cannot access or why it doesnt render.

In the other example doesn't get the data from an API it gets the data from a local object in json. Does it work different when it comes an API? Any idea?

import React, { Component } from "react";

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

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch("https://www.themealdb.com/api/json/v1/1/random.php")
      .then(response => response.json())
      .then(json => {
        this.setState({ recipes: json });
      })
      .catch(error => console.log("parsed error", error));
  }

  render() {
    return <div className="box">{this.state.recipes.strMeal}</div>;
  }
}

export default App;

Your code looks okay, but you need to render somehow your backend data:

fetchData() {
  fetch("https://www.themealdb.com/api/json/v1/1/random.php")
    .then(response => response.json())
    .then(json => {
      this.setState({ recipes: json.meals });
    })
    .catch(error => console.log("parsed error", error));
 }

  render() {
    return (
      <div className="box">
        {this.state.recipes.map(m => <p>{m.strMeal}</p>)}
      </div>
    );
  }

recipes is a json with meals key that is an array. Each element in the array has strMeal key (name of the meal).

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