首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在react中从映射函数中更改组件?

如何在react中从映射函数中更改组件?
EN

Stack Overflow用户
提问于 2019-12-20 18:46:11
回答 3查看 483关注 0票数 0

假设在我的react组件中有一个状态作为

代码语言:javascript
复制
state={
   a:0,
   b:0
}

我也有一个数组arr作为道具进入这个组件。

代码语言:javascript
复制
[{name:"one",category:"a"},{name:"two",category:"b"},{name:"three",category:"a"}]

我想要的是遍历这个数组并检查每个值,如果类别是'a‘然后在我的状态中将值a乘以1,或者如果类别是'b’,那么在我的状态下将b的值增加1。

我到目前为止所做的事:

代码语言:javascript
复制
this.props.arr.map(elem =>{ if(elem.category==='a'){ this.setState({ a:this.state.a+1 }) } })
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-20 18:52:50

使用reduce迭代数组,创建具有ab键的对象,使用匹配的每个类别增加它们的值,然后使用一个操作设置这些值的新状态。

代码语言:javascript
复制
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 });

票数 2
EN

Stack Overflow用户

发布于 2019-12-20 19:06:57

让我们说,您从道具中得到的数组名为“array”。

代码语言:javascript
复制
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 });
  }
})
票数 1
EN

Stack Overflow用户

发布于 2019-12-20 19:22:12

如果您正在使用lodash,您可以这样做countBy:

代码语言:javascript
复制
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 });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59430025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档