[英]How to loop through an array of objects and get specific key values in React?
我想使用forEach
或map
來遍歷具有多個對象的數組。 這些對象具有關鍵price
和價值。 我正在嘗試使用forEach
但無法正常工作。 這是我的組件:
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
值,以便可以將其添加到函數中?
您不應直接將狀態分配給state,而應使用setState
。 forEach
很好,但是我建議您跳過forEach
並map
並使用reduce
,僅將價格鍵從對象中拉出:
countTotal() {
this.setState({
total: this.state.cart.reduce((total, { price }) => total + price, 0)
});
}
要回答如何遍歷數組,可以像使用C之類的語言一樣,在javascript中使用簡單的for
循環。
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(
<div className= "Webcart" id="Webcart">
{ this.countTotal() }
</div>
);
}
}
class App extends Component {
render() {
return (
<Cart cart={
[
{
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)
};
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.