我如何在反应中循环

时间:2018-08-24 03:20:30

标签: reactjs

当我使用map()时,出现此错误“ this.props.getCart.items.map不是函数”

{
 "70": 
  [
    {
      "numberPick": 13,
      "numberPrice": 200
    },
    {
      "numberPick": 44,
      "numberPrice": 300
    }
  ],
 "81": 
  [
   {
     "numberPick": 31,
     "numberPrice": 50
   },
   {
     "numberPick": 22,
     "numberPrice": 90
   },
   {
     "numberPick": 38,
     "numberPrice": 50
   }
  ]
}

这是我如何获得它#redux

 var newData = (state.items[action.parent] === undefined)?[]:state.items[action.parent]
        state = {
            ...state,
            items:{
                ...state.items,
                [action.parent]:[...newData,{
                    numberPick:action.item,
                    numberPrice:action.price
                }]
            }
        }

我想要的结果。应该是这样

您的父母ID是70:

第一:itemID = 13,价格= 200

秒:itemID = 44,价格= 200

您的父母ID是81:

第一:itemID = 31,价格= 50

秒:itemID = 22,价格= 90

任何人都可以帮助我。非常感谢

2 个答案:

答案 0 :(得分:1)

您可以遍历对象:

for (var key in this.props.getCart) {
    if (this.props.getCart.hasOwnProperty(key)) {
        console.log(key + " -> " + this.props.getCart[key]);
        this.props.getCart[key].map(item => {/*return items*/})
    }
}

然后获取数组元素并推入另一个数组。

How do I loop through or enumerate a JavaScript object?

答案 1 :(得分:1)

没有对象的地图,但是您想在下面使用

Object.keys(myObject).map(function(key, index) {
   myObject[key] *= 2;
});

console.log(myObject);

但可以轻松地使用for in ...来迭代对象:

for(var key in myObject) {
    if(myObject.hasOwnProperty(key)) {
        myObject[key] *= 2;
    }
}

在下面的代码中查看您的示例。

class App extends React.Component {

  constructor() {
    super();
    this.state = {
      getCart: {
        "70": [{
            "numberPick": 13,
            "numberPrice": 200
          },
          {
            "numberPick": 44,
            "numberPrice": 300
          }
        ],
        "81": [{
            "numberPick": 31,
            "numberPrice": 50
          },
          {
            "numberPick": 22,
            "numberPrice": 90
          },
          {
            "numberPick": 38,
            "numberPrice": 50
          }
        ]
      }
    }
  }

  render() {
    
    for (var k in this.state.getCart) {
        // console.log(k);
        this.state.getCart[k].map(i => {
            // you want to get induvidual items 
            console.log('items : ', i);
            console.log('numberPick : ', i['numberPick']);
            console.log('numberPrice : ', i['numberPrice']);
      
        })
    }
    
    return (
      <div> check console log</div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>