繁体   English   中英

map()返回未在react组件中呈现

[英]map() return doesn't render in react component

我正在尝试使用JSON数据映射在第二个渲染中渲染数据。 我必须查看两个对象才能找到匹配的product_ids

我在这里做错了什么?

  { 
    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>
      )
    }) 
  } 

在一个旁注中,我知道这是回调地狱,只是不确定如何重构它的最佳方法。

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

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

@BenSteward的答案是正确的。 请注意,有多种方法可以减少嵌套地图。

一种方法是,不用遍历product_ids并遍历其中的products ,您可以遍历products并检查该product的id是否在指定的product_ids 退出

(这是代码的更干净的版本, parenthesis和花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>
  ))
}

我相信它的性能会更好,并且对您将来的自我也更容易理解。

暂无
暂无

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

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