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,
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:
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,
}
}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.