假设我的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 }) } })
最佳答案
使用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 });
关于javascript - 如何在react中从map函数内部更改组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59430025/