简体   繁体   中英

map() return doesn't render in react component

I'm trying to render data in a second render with JSON data mapping over it. I have to look over two objects to find matching product_ids

What am I doing wrong here?

  { 
    this.props.productGroups.map((productGroup) => {
      return (
        <TabContainer key={productGroup.id}>
          <h3>{productGroup.title}</h3>

          {
            productGroup.product_ids.map((productId) => {
              this.props.products.map((product) => {
                if (product.id == productId) {
                  return (
                    <div>
                      test
                    </div>
                  )
                } else {
                  console.log('miss')
                }
              })
            })
          }

        </TabContainer>
      )
    }) 
  } 

On a sidenote, I know this is callback hell, just not to sure on the best way of refactoring this.

您的第一个.map()在this.props....之前缺少返回this.props....

return this.props.products.map((product) => {

@BenSteward's answer is correct. For your side note, there are various ways to lessen the nested maps.

One way would be, instead of looping through product_ids and loop through products inside of it, you can just loop through products and check if that product 's id exits in the specified product_ids :

(This is a cleaner version of your code with less parenthesis and braces )

{
  this.props.productGroups.map(productGroup => (
    <TabContainer key={productGroup.id}>
      <h3>{productGroup.title}</h3>

      {this.props.products.map(product => {
        if (productGroup.product_ids.includes(product.id)) { /* Note this line */
          return <div>test</div>
        }
        console.log('miss')
      })}
    </TabContainer>
  ))
}

I'm sure it's much better in performance and also much more understandable to your future self.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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