看看下面的代码,有没有更好的方法来获取包含特定键/值对的项目在反应状态内的计数?更智能的计算对象(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>