首页 > 解决方案 > TypeError:无法在我的应用程序中读取未定义的属性“地图”

问题描述

每次我尝试映射成分数组时都会出现此错误

这是成分数组

ingredients": [
  "2 jalapeno peppers, cut in half lengthwise and seeded",
  "2 slices sour dough bread",
  "1 tablespoon butter, room temperature",
  "2 tablespoons cream cheese, room temperature",
  "1/2 cup jack and cheddar cheese, shredded",
  "1 tablespoon tortilla chips, crumbled\n"
],

这是我的代码

renderRecipe(){
    const {recipe}= this.props;
    const recipeTitle = recipe.title;
    const publisher = recipe.publisher;
    const ingredients = recipe.ingredients.map((ingredient) => {
        console.log(ingredient);
        return <li key={recipeId}> {ingredient} </li>     
    })

    const recipeId = recipe.recipe_id;
    const recipeImage = recipe.image_url;

    return (
        <div>
            <p>{recipeId}</p>
            <img src={recipeImage} />

           <ul>
               {ingredients}
           </ul>


        </div>
    )

}render() {

return (
  <div>
      {this.renderRecipe()}

  </div>
)}}const mapStateToProps= state => ({
recipe: state.recipe.recipe})export default connect (mapStateToProps)(Recipe)

并且我收到此错误(TypeError:无法读取未定义的属性“地图”)并且没有地图,应用程序可以正常工作

请帮助,谢谢,伙计们

标签: javascriptreactjs

解决方案


很可能在第一次渲染中你还没有填充你的 recipe.ingredients。React 属性有时会晚一些到达,并且在 prop 填充之前运行几次渲染。

进行额外检查以确保您拥有所需的数据。如果不是,您始终可以返回 null 或仅显示加载范围。在通过成分映射之前执行此操作。

if (!this.props.recipe || !this.props.recipe.ingredients || this.props.recipe.ingredients.length === 0) {
    return null;
}

你也可以使用 proptypes.defaultProps 来避免这样的检查。

在长期解决方案中,我还建议创建一个单独的 util 文件,该文件具有如下功能:

export function getVariable(contentObj, name, defaultReturn) {
    const nameChain = name.split('.');
    const resultVariable = nameChain.reduce((levelResultObj, nameElement) => {
        return levelResultObj && levelResultObj.hasOwnProperty(nameElement)
            ? levelResultObj[nameElement]
            : undefined; // eslint-disable-line no-undefined
    }, contentObj);
    return (resultVariable !== undefined) ? resultVariable : defaultReturn;
}

使用此功能,您可以从“深层对象”中获取数据,而无需逐级检查。如果任何级别失败,您可以将返回值作为第三个参数。像这样的东西。

ObjectUtil.getVariable(this, 'props.recipe.ingredients', []);

即使任何级别未定义,这也会返回一个空数组。然后,您可以毫无顾虑地调用 map 来检查它的长度或渲染它不包含任何内容的结果。


推荐阅读