React中的Javascript函数:为什么我的函数不返回多个div?

问题描述 投票:1回答:2

我想为给定对象内的每个项目和密钥对返回一个“hi”div。所以当我在对象中有2对时,我想返回2个div。但是,我只得到1 div返回。为什么会这样?我错过了一些非常明显的东西,我现在才对不起?我怎样才能返回超过1个div?

这是功能:

createList() {
        for(let chosenBook in this.props.updateBasket.productMap) {
            return <div>hi</div>
        }
    }
javascript reactjs function object for-loop
2个回答
3
投票

如果遇到for loop声明,return将退出。你需要的是map超过object keys并返回结果。

createList() {
        return Object.keys(this.props.updateBasket.productMap).map(key => {
            return <div>hi</div>
        });
    }

1
投票
for(let chosenBook in this.props.updateBasket.productMap) {  //wrong syntax
                    return <div>hi</div>
      }

使用of,而不是in

  for(let chosenBook of this.props.updateBasket.productMap) {  //correct syntax
                return <div>hi</div>
  }
© www.soinside.com 2019 - 2024. All rights reserved.