我尝试渲染项目地图时出错

问题描述 投票:0回答:1

我试图找出我的错误在我的反应js页面中的位置

我尝试了不同的东西,比如将它改成状态组件,返回和渲染语句等等。但它仍然给了我

“TypeError:无法读取属性'map'未定义的食谱src / components / Recipes.js:4 1 | import React from”react“; 2 | 3 | const Recipes =(props)=>(4 | 5 | {props。 recipes.map((recipe)=> {6 | return(7 |查看已编译)

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import InputForm from "./components/InputForm";
import Recipes from "./components/Recipes"

const API_KEY= "mykey";

class App extends Component {

  state= {
    recipes: []
  }

  getRecipe  = async (e) => {
  e.preventDefault();
  const recipeName = e.target.elements.recipename.value;
  const api_call = await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${recipeName}&page=2`)

  const data = await api_call.json();
  this.setState({ recipes: data.recipes });
}
  render() {
    return (
      <div className="App">
        <header className="App-header">
          React Cookbook
        </header>
        <InputForm getRecipe={this.getRecipe} />
       <Recipes recipes={this.state.recipes} />
      </div>
    );
  }
}

export default App;

Recipes.js

import React from "react";

const Recipes = (props) => (
    <div>
     { props.recipes.map((recipe)=> {
        return (
        <div key={recipe.recipe_id }>
            <img src={recipe.image_url} alt={recipe.title}/>
            <h3>{ recipe.title }</h3>
         </div>
            )
        })}
    </div>
)

export default Recipes;
javascript reactjs react-native web frontend
1个回答
0
投票

正如Andrew在评论中指出的那样,听起来服务器的响应是undefined,这就是添加到食谱状态对象的内容。您可以在控制台中检查这一点。例如,您的API密钥和配方名称是否有效?您是否正在访问返回数据的正确部分?

另外,recipes中的state在第一次渲染时是空的。您需要在代码中检查这种可能性。在这里,我只返回一个空div,但您可以添加一个加载微调器或其他东西,以便为用户提供有用的反馈。

render() {

  const { recipes } = this.state;

  if (!recipes.length) return <div />;

  return (
    <div className="App">
      <header className="App-header">
        React Cookbook
      </header>
      <InputForm getRecipe={this.getRecipe} />
      <Recipes recipes={recipes} />
    </div>
  );

}
© www.soinside.com 2019 - 2024. All rights reserved.