在 React 组件中使用 map 函数时,我有点困惑。我有一个食谱组件,它从 App 组件获取食谱数据。
应用组件
<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
函数并将输出分配给 render 内的
工作正常。为什么 recipe
变量()renderRecipes
中的 map
函数不返回任何内容?
最佳答案
因为您没有在 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> );
}
When
{}
is required with map?
当您想根据某些条件进行一些计算或返回不同的元素时,请使用 {}
创建一个范围来定义一些变量并使用 if 条件,但在这里您只是想要返回单个元素,因此此处不需要 {}
。
注意:您需要为每个元素分配唯一的key
,这里我使用了索引,但我建议您使用配方对象的任何唯一属性。
关于javascript - React map 函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104784/