gpt4 book ai didi

javascript - 如何从 react 中的 map 函数内部更改组件?

转载 作者:行者123 更新时间:2023-11-28 14:11:03 25 4
gpt4 key购买 nike

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

state={
a:0,
b:0
}

我还有一个数组arr作为进入该组件的 Prop

[{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 键创建一个对象,根据每个匹配的类别增加它们的值,然后通过一个操作使用这些值设置新状态>.

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com