为什么我用 componentDidMount 中的响应填充状态后,应用程序中没有显示食谱

Why is the recipes not showing in the application after I fill in the state with the response in componentDidMount

我调用了this.state.ingredients

的setState方法后页面上没有显示成分数据

我尝试更改代码中的不同参数,例如 res.data.recipes,等等

import React from 'react';
import Form from './RecipeForm';
import axios from 'axios';

const API_KEY = 'f562842f0ff6b2d4fd24b9601aeb5e1b';

class HomeScreen extends React.Component {
  state = {
    ingredients: []
  };

  componentDidMount() {
    axios
      .get(
        'https://www.food2fork.com/api/search?key=f562842f0ff6b2d4fd24b9601aeb5e1b&q=shredded%20chicken'
      )
      .then(res => {
        console.log(res);
        this.setState({
          ingredients: res.data
        });
      });
  }

  render() {
    const recipeList = this.state.ingredients.length ? (
      this.state.ingredients.map(ingredient => {
        return (
          <div key={ingredient.recipe_id}>
            <p>{ingredient}</p>
          </div>
        );
      })
    ) : (
      <div>There are no ingredients here</div>
    );
    return (
      <div style={{ padding: 50 }}>
        <Form />
        <div>{recipeList}</div>
      </div>
    );
  }
}

export default HomeScreen;

我绘制数据的页面没有输出

这是我的console.log

config: {url: "https://www.food2fork.com/api/search?key=bfb76b78b11e7308cc3c027865a508dd&q=shredded%20chicken", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data:
count: 30
recipes: Array(30)
0: {publisher: "Closet Cooking", f2f_url: "http://food2fork.com/view/35171", title: "Buffalo Chicken Grilled Cheese Sandwich", source_url: "http://www.closetcooking.com/2011/08/buffalo-chicken-grilled-cheese-sandwich.html", recipe_id: "35171", …}
1: {publisher: "All Recipes", f2f_url: "http://food2fork.com/view/29159", title: "Slow Cooker Chicken Tortilla Soup", source_url: "http://allrecipes.com/Recipe/Slow-Cooker-Chicken-Tortilla-Soup/Detail.aspx", recipe_id: "29159", …}
2: {publisher: "My Baking Addiction", f2f_url: "http://food2fork.com/view/e7fdb2", title: "Mac and Cheese with Roasted Chicken, Goat Cheese, and Rosemary", source_url: "http://www.mybakingaddiction.com/mac-and-cheese-roasted-chicken-and-goat-cheese/", recipe_id: "e7fdb2", …}```

在您的 componentDidMount 中,您需要将 ingredients 设置为 res.data.receipes 而不是 res.datares.data 只是服务器的响应负载。如果你想访问里面的一些数据,你必须进一步索引响应对象。但是,这并不总是好的,因为有时(如果发生错误)recipes 可能不存在。在那种情况下,你应该有一个 catch 块(就像在 Axios docs 中一样)。

this.setState({
  ingredients: res.data.receipes
});