繁体   English   中英

如何在反应中从地图函数内部更改组件?

[英]How do I change the component from inside a map function in 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迭代数组以创建一个带有ab键的对象, a匹配的每个类别增加它们的值,然后使用这些值通过一次操作设置新状态。

 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 });

假设你的 props 数组带有一个名为“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 });
  }
})

如果您使用 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 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM