簡體   English   中英

React不呈現API數據

[英]React doesn't render API data

我正在構建一個食譜應用程序,我陷入了困境,沒有錯誤顯示或任何可以幫助我的東西,這是我第一次在React和Im中使用API​​S,這就是我問的原因。

我正在嘗試從此API提取數據, 我不知道為什么屬性不會顯示在屏幕上,因為我還有另一個示例。

我可以在帶有React Developer擴展的控制台中看到將屬性傳遞給狀態,這樣很好,而且我不明白為什么我不能訪問或為什么它不能呈現。

在另一個示例中,它不是從API獲取數據,而是從json中的本地對象獲取數據。 使用API​​時,它的工作原理是否有所不同? 任何想法?

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;

您的代碼看起來還不錯,但是您需要以某種方式呈現后端數據:

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是帶有meals鍵的json,是數組。 數組中的每個元素都有strMeal鍵(餐名)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM