假设在我的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 }) } })发布于 2019-12-20 18:52:50
使用reduce迭代数组,创建具有a和b键的对象,使用匹配的每个类别增加它们的值,然后使用一个操作设置这些值的新状态。
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 });
发布于 2019-12-20 19:06:57
让我们说,您从道具中得到的数组名为“array”。
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 });
}
})发布于 2019-12-20 19:22:12
如果您正在使用lodash,您可以这样做countBy:
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 });https://stackoverflow.com/questions/59430025
复制相似问题