假设我的react组件中的状态为
state={
a:0,
b:0
}
我也有一个数组arr
作为这个组件的道具
[{name:"one",category:"a"},{name:"two",category:"b"},{name:"three",category:"a"}]
我想要的是遍历此数组,并检查类别是否为'a'的每个值,然后在我的状态下将值a增加1,否则,如果类别为'b',则将b的值增加1在我的状态。
到目前为止我所做的:
this.props.arr.map(elem =>{ if(elem.category==='a'){ this.setState({ a:this.state.a+1 }) } })
答案 0 :(得分:2)
使用reduce
遍历数组以创建具有a
和b
键的对象,并在每个匹配的类别中增加其值,然后使用< em>一项操作。
const arr = [{name:"one",category:"a"},{name:"two",category:"b"},{name:"three",category:"a"}];
// Desctructure `a` and `b` from the result of the
// reduce operation
const { a, b } = arr.reduce((acc, c) => {
// For each iteration destructure `category` from the current object
// in the array, increase the value in the accumulator
// that matches that category, and return the accumulator
// for the next iteration
const { category } = c;
++acc[category];
return acc;
// Initialise the accumulator with an object
// with `a` and `b` set to zero
}, {a: 0, b: 0 });
console.log(a, b);
// set the state with the new values of `a` and `b`
// this.setState({ a, b });
答案 1 :(得分:1)
让我们说,您从道具中获得的数组带有“数组”的名称
this.props.array.map(item => {
if (item.category === 'a') {
this.setState({ a: this.state.a + 1 });
} else if (item.category === 'b') {
this.setState({ a: this.state.b + 1 });
}
})
答案 2 :(得分:1)
如果您使用lodash,则可以这样计数:
const arr = [{name:"one",category:"a"},{name:"two",category:"b"},{name:"three",category:"a"}];
const {a, b} = _.countBy(a,"category")
// set the state with the new values of `a` and `b`
// this.setState({ a, b });