反应地图功能混乱

时间:2017-05-22 04:39:44

标签: javascript reactjs dictionary

在React Component中使用它时,我对map函数有点困惑。我有一个食谱组件,它从App组件传递食谱数据。

APP COMPONENT

<Recipes recipes={recipes} />

食谱组件

export default class Recipes extends Component {
  // THIS FUNCTION IS RETURNING NOTHING
  renderRecipes() {
    return this.props.recipes.map((recipe) => {
      <h1>{recipe.name}</h1>
    });
  }
  render() {
    let recipe = this.props.recipes.map((recipe) => {
      return (
        <h1>{recipe.name}</h1>
      );
    });
    return(
      <div>
        // CALLING THE FUNCTION HERE DOES NOT WORK
        { this.renderRecipes() }
        // HOWEVER CALLING THE VARIABLE DOES WORK
        { recipe }
      </div>
    );
  }
}

这是我感到困惑的地方。创建一个执行map函数的函数不会返回任何内容,但是移动map函数并将输出分配给recipe内的render()变量可以正常工作。为什么map中的renderRecipes函数什么都没有返回?

1 个答案:

答案 0 :(得分:2)

因为你没有在map身体内返回任何内容,所以请按照以下方式使用它:

renderRecipes() {
    return this.props.recipes.map((recipe, i) => {
        return <h1 key={i}> {recipe.name} </h1>
    });
}

或删除{}

renderRecipes() {
    return this.props.recipes.map((recipe, i) => <h1 key={i}> {recipe.name} </h1> );
}
  

地图需要{}吗?

当您想要进行某些计算或想要根据某些条件返回不同的元素时,请使用{}创建一个范围来定义一些变量并使用if条件,但在这里您只想返回一个单个元素,因此此处不需要{}

注意:您需要为每个元素分配唯一的key,这里我使用了索引,但我建议您使用配方对象的任何唯一属性。

相关问题