我正在学习 React 并遇到了这段代码:
{this.state.sections.map(({title, imageUrl, id, size}) => (
<MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/>
))}
问题是如何在map()内部使用解构,也就是说,我假设这是解构map(({title, imageUrl, id, size}) =>
对吗?
最佳答案
是的,这叫做解构,具体来说object destructoring 。
Array.map就像一个循环,它当时提供该数组的每个项目。
想象这些数组项是具有很多属性的对象,但您只需要其中很少的属性,在这种情况下,您可以使用析构来仅选择您需要的属性。
例如:
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
})
关于javascript - 对 React 中如何使用 map() 的方式感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60473366/