0

调用 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", …}```
4

1 回答 1

0

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

this.setState({
  ingredients: res.data.receipes
});
于 2019-09-17T20:20:22.770 回答