javascript - 对 React 中如何使用 map() 的方式感到困惑

标签 javascript reactjs

我正在学习 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/

相关文章:

javascript - 为字符串中的相同元素着色

javascript - 在 jQuery 中执行此过程的最有效方法是什么?

javascript - javascript 中的多个文件值

javascript - 在 React 组件之前等待外部脚本加载

javascript - 如何更改 React 组件中的 CSS 高度?

javascript - 如何移动react js中的第二个组件?

javascript - 在 Play 模板中混合使用 JavaScript 和 Scala

javascript - 我怎样才能压缩这个 jQuery 代码?

javascript - React Js - 从字符串创建组件不起作用

javascript - 切换状态在 react 中采用先前的值?