简体   繁体   English

React array.map()

[英]React array.map()

I will use this example http://codepen.io/lacker/pen/vXpAgj , since it's very similar to my current issue. 我将使用此示例http://codepen.io/lacker/pen/vXpAgj ,因为它与我当前的问题非常相似。 So, let's say we have this array: 所以,假设我们有这个数组:

[
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
]

How can I rewrite the code below using array.map()? 如何使用array.map()重写下面的代码?

    var rows = [];
    var lastCategory = null;
    this.props.products.forEach(function(product) {
      if (product.category !== lastCategory) {
        rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
      }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    });    

The sample below doesn't do the job properly. 以下示例无法正常完成工作。

const lastCategory = null;
const rows = this.props.products.map(function(product){     
  if (product.category !== lastCategory) {        
    return (<ProductCategoryRow category={product.category} key={product.category} />); 
  }     
 return (<ProductRow product={product} key={product.name} />); 
 lastCategory = product.category;      
});

Cheers and thank you, 干杯谢谢你,

You'll never be setting the lastCategory because you're always returning before that line. 你永远不会设置lastCategory因为你总是在该行之前返回。 Try moving it up into your block that will be ran if the category is different from the last category. 如果类别与上一类别不同,请尝试将其移动到将运行的块中。

Additionally, like another answer stated, you need to return the category row in addition to the product row when you encounter a new category. 此外,与所述的另一个答案一样,当您遇到新类别时,除了产品行之外,还需要返回类别行。

var lastCategory = null;
const rows = this.props.products.map(function(product){     
  if (product.category !== lastCategory) {
    lastCategory = product.category;
    return (<ProductCategoryRow category={product.category} key={product.category} />
            <ProductRow product={product} key={product.name} />); 
  }     
  return (<ProductRow product={product} key={product.name} />); 
});

forEach方法可以工作,因为可以在一次迭代中将两个元素推送到rows中,这在使用map()返回时是不可能的,因为在一次迭代中只能返回一个要推送的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM