小编典典

React.js正确的方法来遍历对象而不是Object.entries

reactjs

我不喜欢使用它,Object.entries(object).map((key, i)因为我发现这是ECMAScript
7的一项实验技术,我觉得生产中可能会出问题。有没有其他原生javascript替代品?

我对名称,价格,描述值没有任何问题,因为我确切地知道应在何处呈现它们,并且可以使用Populate.key访问它们,但是对于特性,我需要对对象进行扫盲并同时呈现键和值。

我尝试使用,Object.keys(priceChars).map(function(key, i)但不了解如何将键与值分开。就像,它渲染了“性能500”,但我需要性能字在图标类中,而500是要显示的实际值。

我的JSON结构

const Populate = {
  'name': "Product",
  'price': "1000",
  'description': "Product description",
  'characteristics': {
    'performance': '500',
    'pressure': '180',
    'engine': '4',
    'size': '860*730*1300',
    'weight': '420'
  }
}

和组件

class PriceBlock extends Component {
  render() {
    const {priceName, priceDesc, priceVal, priceChars} = this.props;
    const characteristics = Object.entries(priceChars).map((key, i) => {
      return (
        <div className="price__icon-row" key={i}>
          <i className={'ico ico-' + key[0]}></i> <span>{key[1]}</span>
        </div>
      );
    });
    return (
      <div className="col-5 price__block">
        <div className="price__name">{priceName}</div>
        <div className="price__description">{priceDesc}</div>
        <div className="price__icons">
          {characteristics}
        </div>
        <div className={ managePriceClass(priceVal) }>{priceVal}</div>
      </div>
    );
  }
}

阅读 706

收藏
2020-07-22

共1个答案

小编典典

a = { 
  a: 1,
  b: 2,
  c: 3
}

Object.keys(a).map(function(keyName, keyIndex) {
  // use keyName to get current key's name
  // and a[keyName] to get its value
})

使用解构和箭头功能的较新版本。我将这个用于新代码:

a = { 
  a: 1,
  b: 2,
  c: 3
}

Object.entries(a).map(([key, value]) => {
    // Pretty straightforward - use key for the key and value for the value.
    // Just to clarify: unlike object destructuring, the parameter names don't matter here.
})
2020-07-22