简体   繁体   English

通过在React中使用循环来使用setstate

[英]Use setstate by using the loop in react

I have two array of objects. 我有两个对象数组。 I want to setState of an variable by looping through this two arrays. 我想通过遍历这两个数组来设置变量的状态。

I have a state , 我有一个状态,

this.state = {  selectedValue: {} }

I have this two array of objects , 我有这两个对象数组,

this.props.untracked.content && `this.props.tracked.content`

What I did to setstate is , 我要设定的状态是

this.setState({
        selectedValue: {
          ...this.state.selectedValue,
          [`${resumeId}`]: type
        }
      }

In another place where I was not required to loop . 在另一个不需要循环的地方。 Now I need to loop through this two and then I need to setState, 现在我需要遍历这两个,然后需要setState,

for loop I did , 我做了循环

for (const item of 

[...this.props.untracked.content,...this.props.tracked.content]) {
    this.setState({
     selectedValue: {
          ...this.state.selectedValue,
          [`${item.id}`]: item.value
        }
})    
}

So, Can any one help me with this ? 那么,有人可以帮助我吗? Thanks. 谢谢。

要做到这一点,最简单的方法是做所有的处理没有setState和使用setState一次底。

Use setState(oldState => newState) when new state depends on the current one: 当新状态取决于当前状态时,请使用setState(oldState => newState)

this.setState(oldState => ({
     selectedValue: {
          ...oldState.selectedValue,
          [`${item.id}`]: item.value
     }
}));

Also it is better to prepare all updates beforehand: 另外最好事先准备所有更新:

const updates = {};
for (const item of 
    [...this.props.untracked.content,...this.props.tracked.content]
) {
    updates[item.id] = item.value;
}

this.setState(oldState => ({
     selectedValue: {
          ...oldState.selectedValue,
          ...updates,
     }
}));

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

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