Javascript 对React中map()的使用方式感到困惑
我在学习React时遇到了以下代码:Javascript 对React中map()的使用方式感到困惑,javascript,reactjs,Javascript,Reactjs,我在学习React时遇到了以下代码: {this.state.sections.map(({title, imageUrl, id, size}) => ( <MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/> ))} {this.state.sections.map({title,imageUrl,id,size})=>( ))} 问题是如何在map()内部使用destructuring,也就
{this.state.sections.map(({title, imageUrl, id, size}) => (
<MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/>
))}
{this.state.sections.map({title,imageUrl,id,size})=>(
))}
问题是如何在map()内部使用destructuring,也就是说,我假设这是destructuring
map(({title,imageUrl,id,size})=>
对吗?是的,具体地说,它被称为destructoring
类似于一个循环,它同时提供该数组的每个项
假设这些数组项是具有很多属性的对象,但您只需要很少的属性,在这种情况下,您可以使用析构函数来选择您需要的属性
例如:
const array = [
{a: 1, b: 2, c: 3, d: 4},
{a: 5, b: 6, c: 7, d: 8},
{a: 9, b: 8, c: 7 ,d: 6},
{a: 5, b: 4, c: 3, d: 2}
]
// Now we will loop over those items
array.map(item => {
// item here is is one of the objects like this: {a: 1, b: 2, c: 3, d: 4},
// but let's say you need only a and b properties
})
// In that case you can use destructoring
// instead of getting the entire item object you will get only a and b
array.map({a, b} => {
// here you can use a and b as normal variables.
// ex. for this item - {a: 1, b: 2, c: 3, d: 4}
// a -> 1
// b -> 2
})
为什么不能在
map
中执行此操作?-map
与不允许有什么不同?map为数组中的每个元素调用提供的函数,如果每个项都是对象,则可以使用解构。@JuniusL.,很好的解释:),谢谢