React 中渲染数组.map() 时出现错误。

huangapple go评论99阅读模式
英文:

Error while rendering an array.map() in React

问题

我对React非常新,这可能是一个愚蠢的问题,但我收到了一个错误消息:在尝试显示每个食谱的成分时出现错误,错误消息是:“Uncaught TypeError: 无法读取未定义属性 'map'。我不确定是否可以在返回语句内部使用数组.map,或者如果它是我的组件的一部分,我应该在哪里包含它?我只是想浏览成分并显示它们。感谢任何帮助!React 中渲染数组.map() 时出现错误。

import React, { Component } from "react";

class Recipe extends Component {
    state = {
        activeRecipe: []
    }
    componentDidMount = async() => {
        const title = this.props.location.state.recipe;
        const req = await fetch
        (`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);

        const res = await req.json();
        this.setState({ activeRecipe: res.hits[0].recipe});
        console.log(this.state.activeRecipe);
    }
    render() {
        const recipe = this.state.activeRecipe;
        return (
           <div className="container">
               <div className="active-recipe">
                   <h3 className="active-recipe">{recipe.label}</h3>
                   <div className="container">
                   {recipe.ingredients && recipe.ingredients.map(ingredient => {
                    return (
                        <p>{ingredient.text}</p>
                    );
                   })}
                   </div>
               </div>
           </div>
        );
    }
}

export default Recipe;



<details>
<summary>英文:</summary>

I&#39;m super new to React and this might be a dumb question but I&#39;m getting an error saying: `Uncaught TypeError: Cannot read property &#39;map&#39; of undefined
` when I&#39;m trying to display the ingredients for each recipe. I&#39;m not sure if I can use an array.map inside of the return statement, or where else should I include it, if it is a part of my component? I just want to go through the ingredients and display them . Thanks for any help![![Screenshot of my console][1]][1]

import React, { Component } from "react";

class Recipe extends Component {
    state = {
        activeRecipe: []
    }
    componentDidMount = async() =&gt; {
        const title = this.props.location.state.recipe;
        const req = await fetch
        (`https://api.edamam.com/search?q=${title}&amp;app_id=${API_ID}&amp;app_key=${API_KEY}`);

        const res = await req.json();
        this.setState({ activeRecipe: res.hits[0].recipe});
        console.log(this.state.activeRecipe);
        }
        render() {
            const recipe = this.state.activeRecipe;
            return (
               &lt;div className=&quot;container&quot;&gt;
                   &lt;div className=&quot;active-recipe&quot;&gt;
                       &lt;h3 className=&quot;active-recipe&quot;&gt;{recipe.label}&lt;/h3&gt;
                       &lt;div className=&quot;container&quot;&gt;
                       {recipe.ingredients.map(ingredient =&gt; {
                        return (
                            &lt;p&gt;{ingredient.text}&lt;/p&gt;
                        );
                       })}
                       &lt;/div&gt;
                   &lt;/div&gt;
               &lt;/div&gt;
            );
        }
}

export default Recipe;

  [1]: https://i.stack.imgur.com/0SFSZ.png

</details>


# 答案1
**得分**: 1

这是因为您的组件在异步调用完成之前已呈现/挂载。如果您将以下代码更改为:

```jsx
recipe.ingredients && recipe.ingredients.map(ingredient => {

它应该按您想要的方式工作。这是因为只有在存在ingredients时才会调用map方法。

英文:

This is because your component is rendered/mounted before the async call can finish..

If you change:

recipe.ingredients.map(ingredient =&gt; {

to this:

recipe.ingredients &amp;&amp; recipe.ingredients.map(ingredient =&gt; {

It should work as you are wanting.

This is because map does not get called unless ingredients exist.

huangapple
  • 本文由 发表于 2020年1月4日 01:57:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定