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
属性为 null
或 undefined
,则使用空数组
关于javascript - 由于 TypeError : Cannot read property 'map' of null,React 页面未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54406101/