2017-08-02 29 views
0

我想要使用forEachmap来遍历其中有多个对象的数组。这些对象有一个密钥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> 
     ); 
    } 
} 

... 

countTotalconsole.log(this.state.items)每一个看起来像

item:"Hoodie" 
price:25 
size:"large" 

我遍历每个对象,怎样才能获得price值,所以我可以将它添加了输出的各种对象我功能?

+0

的[有没有其他的方式,以避免阵营forceUpdate](可能的复制https://stackoverflow.com/questions/45187529/is-there-any-other-way-to-avoid-react-forceupdate) –

回答

0

要回答如何通过数组循环,你可以使用一个简单for循环在JavaScript中,你会用像C这样的语言;

let total = 0; 
for(let i = 0; i < items.length; i++) { 
    total += item[i].price 
} 

阵营以下功能的做法,我们更喜欢mapreduce,因为它使你的代码更具声明。因此,

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; 

注 没有使用setStatetotal是派生数据。派生数据不能驻留在状态中。

然而,如果由于某种原因,你仍然需要它,countTotal是这样的,

countTotal() { 
    this.setState(state => { 
    return { 
     total: state.items.reduce((acc, item) => { 
      return acc + item.price; 
     }, 0) 
    }; 
    }); 
} 
3

您不应该直接指定状态,而应该使用setStateforEach是好的,但我会建议你跳过forEachmap和使用reduce,只是拉动价格抠出的对象:

countTotal() { 
    this.setState({ 
     total: this.state.cart.reduce((total, { price }) => total + price, 0) 
    }); 
} 
+0

如果我在'this.setState(){'后得到'console.log(this.state.total)'''' 0 .. – feners

+0

setState是异步的,你的控制台日志会在它完成之前触发。把控制台日志放在渲染方法中,或者渲染总数为 –

+0

我建议在访问'this.state'来计算新状态时使用'setState'的回调形式:'this.setState(prevState =>({total :prevState.cart.reduce((total,{price})=> total + price)});' – rossipedia

相关问题