map
的所有文档都使用大括号,但下面的代码和我在处理React时使用的大多数示例都使用括号。我正在试图找出差异是什么以及代码在做什么。
使用大括号时,除非我专门添加return
,否则不会渲染。所以我的看法是括号作为某种内联函数自动返回或React转换结果并将其内联到JSX中?
// Renders fine
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) => (
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
) )
}
</div>
);
}
// Nothing
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) =>
{
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
}
</div>
);
}
// Renders fine
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) =>
{
return <ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
}
</div>
);
}
与React无关,它与javascript有关
卷曲括号说它是一个函数体,所以我们需要手动使用return
关键字
this.props.items.map(
( _item, _index ) =>
{ // Note: represent function body, normal javascript function
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
根据arrow functions
,具有隐式返回行为因此需要明确提及单行表达式。
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) => ( // Note: single line expression, so impilicit;y return our ItemComponent
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
) )
}
</div>
);
}
因此,箭头函数中的括号返回单个值,在执行多行代码时使用花括号而不仅仅是简单的返回,因此需要手动返回语句,因为javascript无法知道这些行中的哪些行返回。
materials.map(material => ({key:material.name}));
返回一个对象
materials.map(material => {
let newMat = material.name+'_new';
return newMat;
});
我们需要返回,因为我们正在做一行或多行操作并试图返回最终结果