TypeError:无法读取我的应用中未定义的属性“ map”

时间:2018-11-30 08:41:24

标签: javascript reactjs

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

这是成分数组

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:无法读取未定义的属性“ map”) 并且没有地图,该应用程序可以正常运行

请帮助, 谢谢,伙计们

2 个答案:

答案 0 :(得分:2)

很可能在第一个渲染中,您还没有添加配方。 React属性有时会晚些到达,并且在填充道具之前运行几次渲染。

进行其他检查,以确保您具有必需的数据。如果不是,则可以始终返回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', []);

这将返回一个空数组,即使未定义任何级别。然后,您可以调用地图而不必担心检查其长度或使结果不包含任何内容。

答案 1 :(得分:0)

有一些原因。 起初this.props.ingredients不会被定义。 因此,您要自己检查this.props.ingredients的有效性。

const {recipe}= this.props; console.log(recipe.ingredients);

然后您可以通过添加if statement

来解决问题。

例如

let ingredients;
if(recipe.ingredients !== undefined && ricipe.ingredients.length > 0)
{
    ingredients = recipe.ingredients.map((ingredient) => {
        console.log(ingredient);
        return <li key={recipeId}> {ingredient} </li>     
    })
}
else
    ingredient = null;