【问题标题】:Losing key value pair in react when mapping over props映射道具时在反应中丢失键值对
【发布时间】:2020-10-06 19:09:25
【问题描述】:

在向 API 发出多个请求后,我 promise.all() 那个请求并发出另一个请求,坚持上次请求的一些属性。这给了我:

(4) [{…}, {…}, {…}, {…}]
0: {product_id: "2", results: Array(4), productInfo: {…}}
1: {product_id: "3", results: Array(6), productInfo: {…}}
2: {product_id: "8", results: Array(9), productInfo: {…}}
3: {product_id: "7", results: Array(5), productInfo: {…}}
length: 4
__proto__: Array(0)

productInfo: {...} 是我想要的键值对。在底部的这个组件中,我console.log() 对象出现了,但随后它在map() 中丢失了?为什么会这样,我该如何解决?

const FormatRelated = ({ recommended }) => {
  //  eslint-disable-next-line no-console
  console.log(recommended)
  return (
    <div className="recommendedThumbNailsRow">
      {recommended.map(obj => {
        //  eslint-disable-next-line no-console
        console.log(obj);
        return <DisplayRelatedImg styles={obj} />;
      })}
    </div>
  );
};

【问题讨论】:

  • Edit-im 已经映射到一个数组上,因为前一个组件中的状态是一个数组

标签: javascript reactjs data-binding promise axios


【解决方案1】:

Map 函数是一个数组函数Array Map

如果你想遍历对象道具,你应该使用这样的东西:

Object.keys(recommended).map(key => console.log(recommended[key]))

【讨论】:

  • 我的错误我没有指定我已经映射到一个数组
猜你喜欢
  • 2019-05-31
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
相关资源
最近更新 更多