javascript - 由于 TypeError : Cannot read property 'map' of null,React 页面未加载

标签 javascript css reactjs frontend

import React from 'react';

import { Link } from "react-router-dom";

const Recipes = props => (
    <div className="container">
        <div className="row">
            {props.recipes.map((recipe) => {
                return (
                    <div key={recipe.title} className="col-md-4" style={{ marginBottom: "2rem" }}>
                        <div className="recipes__box">
                            <img
                                className="recipe__box-img"
                                src={recipe.image_url}
                                alt={recipe.title} />
                            <div className="recipe__text">
                                <h5 className="recipes__title">
                                    {recipe.title.length < 20 ? `${recipe.title}` : `${recipe.title.substring(0, 25)}...`}
                                </h5>
                                <p className="recipes__subtitle">Publisher: <span>
                                    {recipe.publisher}
                                </span></p>
                            </div>
                            <button className="recipe_buttons">
                                <Link to={{
                                    pathname: `/recipe/${recipe.recipe_id}`,
                                    state: { recipe: recipe.title }
                                }}>View Recipe</Link>
                            </button>
                        </div>
                    </div>
                );
            })}
        </div>
    </div>
);

export default Recipes;

谁能告诉我为什么我的 .map() 函数会导致此错误?这是我要遵循的教程(构建一个食谱 react 元素) 这是源代码: https://github.com/hamza-mirza/react-recipe-app/blob/master/src/components/Recipe.js

我的和下面的一样,但我得到了 TypeError。

最佳答案

看起来您的 recipes 属性在第一次呈现时为 null。 也许您正在传递以异步方式填充的内容,并且在第一次渲染时还不存在。

尝试在你的代码中添加:

(props.recipes || []).map

为了进行安全检查包装,如果在第一次渲染时 recipes 属性为 nullundefined,则使用空数组

关于javascript - 由于 TypeError : Cannot read property 'map' of null,React 页面未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54406101/

相关文章:

javascript - React-router条件渲染

javascript - 单击 'finished' 时 FuelUX 向导未提交我的表单

javascript - 未捕获的类型错误 : b. toLowerCase 不是函数

javascript - 使用 Node.Js 的 Lambda 函数

java - 禁用 HTML 输入时的 NullPointer

html - 多文本应该在悬停状态下一起改变

javascript - 如何在点击时更改按钮图标?

javascript - 如何在 React 组件中导入图像(.svg、.png)

javascript - 将 GrapesJS 与 React JS 集成

javascript - for/if 循环根据 input::jquery 多次运行一个函数