如何在React.js的迭代中处理SetState函数

时间:2019-04-04 07:04:37

标签: reactjs

当我在for循环中使用setState函数时,它仅在每个子组件值中分配数组的最后一个值。如何使它分配具有相应索引的值。

class App extends Component {
  constructor() {
    super();
    this.postID = "";
    this.value = 0;
    this.name = "";

    this.state = {
      countersarray: []
    };
  }
  componentDidMount() {
    this.loadData();
  }
  //load data as from array
  loadData = countersarray => {
    var nam = ["Haseeb", "Fawad", "Khan"];
    var elements = "";
    var count = 0;

    for (var i = 0; i < nam.length; i++) {
      elements = nam[i];
      this.setState(previousState => ({
        countersarray: [
          ...previousState.countersarray,
          (countersarray = {
            key: uniqeid(),
            id: uniqeid(),
            value: 0,
            name: elements
          })
        ]
      }));
    }
  };

我希望输出的名称不同,但实际输出的名称相同。

状态

countersarray:[{id:"ju2a3ex7", key:"ju2a3ex6",name:"Khan",value:0},
               {id:"ju2a3ex9",key:"ju2a3ex8",name:"Khan",value:0},
               {id:"ju2a3exb",key:"ju2a3exa",name:"Khan",value:0}]

预期

countersarray:[{id:"ju2a3ex7", key:"ju2a3ex6",name:"Haseeb",value:0},
               {id:"ju2a3ex9",key:"ju2a3ex8",name:"Fawad",value:0},
               {id:"ju2a3exb",key:"ju2a3exa",name:"Khan",value:0}]

2 个答案:

答案 0 :(得分:0)

请勿在{{1​​}}中使用setState。或者,您也可以尝试

for..loop

答案 1 :(得分:0)

通过使用.map函数进行少量更改即可解决该问题。

 loadData = countersarray => {
    var name = ["Haseeb", "Fawad", "Khan"];
    countersarray = [
      ...this.state.countersarray,
      ...name.map(
        nm =>
          (countersarray = {
            key: uniqeid(),
            id: uniqeid(),
            value: 0,
            name: nm
          })
      )
    ];