2016-10-08 30 views
0

看看下面的代码,有没有更好的方法来获取包含特定键/值对的项目在反应状态内的计数?更智能的计算对象(JS,React)值的方法

这种方法似乎可能会导致瓶颈,一旦我经历的列表变得很大。

下面是手头上的问题的一个简单的例子:

class App extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    
 
    this.state = { 
 
     animals: [ 
 
     {type: 'cat'}, 
 
     {type: 'dog'}, 
 
     {type: 'cat'}, 
 
     ] 
 
    }; 
 
    } 
 

 
    render() { 
 
    return(
 
     <div className="app"> 
 
     <Categories state={this.state} /> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
class Categories extends React.Component { 
 
    constructor() { 
 
    super(); 
 

 
    this.countItems = this.countItems.bind(this); 
 
    } 
 

 
    countItems(type) { 
 
    var count = 0; 
 
    
 
    for(var i = 0; i < this.props.state.animals.length; i++) { 
 
     if(this.props.state.animals[i].type === type) { 
 
     count++; 
 
     } 
 
    } 
 
    
 
    return count; 
 
    } 
 

 
    render() { 
 
    return(
 
     <div className="categories"> 
 
     <div>Total animals: {this.props.state.animals.length}</div> 
 
     <div>Cats: {this.countItems('cat')}</div> 
 
     <div>Dogs: {this.countItems('dog')}</div> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<App />, document.getElementById('container'));
<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="container"></div>

回答

1

如果这是你经常会调用一个方法,那么它可能是你的数据(动物)的有用指标键入,并在更改时保持更新。

例如:

App构造函数中,您将创建另一个属性animalsPerType

constructor() { 
    super(); 

    this.state = { 
     animals: [ 
     {type: 'cat'}, 
     {type: 'dog'}, 
     {type: 'cat'}, 
     ] 
    }; 
    this.state.animalsPerType = this.state.animals.reduce(function(acc, animal) { 
     return acc.set(animal.type, (acc.get(animal.type) || []).concat(animal)); 
    }, new Map()); 
    } 

那么你countItems方法变得微不足道:

countItems(type) { 
    return this.props.state.animalsPerType.get(type).length; 
    } 
1

如果你不改变你的结构状态,那么你必须做一些循环的通过并计数类型。

一个更具表现力的方法可能是使用减少:

countItems(type) { 
    return this.props.state.animals.reduce((acc, next) => { 
     return next.type == type ? acc + 1 : acc) 
    }, 0); 
    } 

然而,如果性能是一个问题:

  1. 你可以保持状态的计数和计算一次,每次animals变化

  2. 你可以将每种动物分成一个独立的状态数组,然后在eac上使用length H。

  3. 改变你的状态有点像这可能帮助:

this.state = { animals: { dogs: [], cats: [] } }

相关问题