我想要使用forEach
或map
来遍历其中有多个对象的数组。这些对象有一个密钥price
及其值。我正在尝试使用forEach
,但我无法使其工作。这是我的组件:如何遍历对象数组并获取React中的特定键值?
import React, { Component } from 'react';
import {addCart} from './Shop';
import { connect } from 'react-redux';
export class Cart extends Component {
constructor(props) {
super(props);
this.state = {items: this.props.cart,cart: [],total: 0};
}
...
countTotal() {
this.state.cart.forEach((item, index) => {
console.log(this.state.items);
this.state.total = this.state.total + this.state.items.price;
console.log(this.state.total);
})
}
...
render() {
return(
<div className= "Webcart" id="Webcart">
</div>
);
}
}
...
在countTotal
,console.log(this.state.items)
每一个看起来像
item:"Hoodie"
price:25
size:"large"
我遍历每个对象,怎样才能获得price
值,所以我可以将它添加了输出的各种对象我功能?
的[有没有其他的方式,以避免阵营forceUpdate](可能的复制https://stackoverflow.com/questions/45187529/is-there-any-other-way-to-avoid-react-forceupdate) –