簡體   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