要回答如何通过数组循环,你可以使用一个简单for循环在JavaScript中,你会用像C这样的语言;
let total = 0;
for(let i = 0; i < items.length; i++) {
total += item[i].price
}
阵营以下功能的做法,我们更喜欢map和reduce,因为它使你的代码更具声明。因此,
const total = items.reduce((acc, item) => {
return acc + item.price;
}, 0)
你的代码是这样的话,
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
export class Cart extends Component {
constructor(props) {
super(props);
this.state = {items: props.cart,cart: [],total: 0};
}
countTotal() {
return this.state.items.reduce((acc, item) => {
return acc + item.price;
}, 0)
}
render() {
return(
{ this.countTotal() }
);
}
}
class App extends Component {
render() {
return (
[
{
item:"Hoodie",
price:25,
size:"large"
},
{
item:"Gloves",
price: 12,
size:"large"
},
{
item:"boots",
price:30,
size:"large"
},
]
} />
);
}
}
export default App;
注 没有使用setState。 total是派生数据。派生数据不能驻留在状态中。
然而,如果由于某种原因,你仍然需要它,countTotal是这样的,
countTotal() {
this.setState(state => {
return {
total: state.items.reduce((acc, item) => {
return acc + item.price;
}, 0)
};
});
}