I've got a function that I run in the forEach
loop in the child ponent, the function has to filter the data and update the state with the result.
The problem is that when I iterate the function with a loop it running all at the same time and within this, the state will not update properly with data.
The question is how to implement it better, probably there is a way with Promise or async /await or maybe something simpler that will make a work. As needed to put in the queue and wait until the state will be updated.
Simplified code is here
ponent child
this.props.data.forEach((item, i) => {
this.props.update(item);
});
ponent parent
function update(data) {
let filtered = this.state.data.filter(item => item.uid !== data.uid);
this.setState({data: filtered});
}
I've got a function that I run in the forEach
loop in the child ponent, the function has to filter the data and update the state with the result.
The problem is that when I iterate the function with a loop it running all at the same time and within this, the state will not update properly with data.
The question is how to implement it better, probably there is a way with Promise or async /await or maybe something simpler that will make a work. As needed to put in the queue and wait until the state will be updated.
Simplified code is here
ponent child
this.props.data.forEach((item, i) => {
this.props.update(item);
});
ponent parent
function update(data) {
let filtered = this.state.data.filter(item => item.uid !== data.uid);
this.setState({data: filtered});
}
Share
Improve this question
edited Aug 28, 2017 at 8:45
Constantine Golub
asked Aug 28, 2017 at 7:58
Constantine GolubConstantine Golub
3517 silver badges22 bronze badges
2
- Could you please explain what you're trying to achieve with this behaviour? Why not just update the state after you're running your loop? – Daniel Andrei Commented Aug 28, 2017 at 8:10
- @DanielAndrei Sorry, have updated the example, so the state should be updated with filtered variable. – Constantine Golub Commented Aug 28, 2017 at 8:13
2 Answers
Reset to default 2If i understand well you need something like this:
update = () => {
let filtered = this.state.data.filter(x => this.props.data.every(y => x.uid !== y.uid))
this.setState({
data: filtered
})
}
Why not iterating through your array in your parent ponent?
Child:
this.props.update(this.props.data); // pass the entire array
Parent:
function update(data) {
let filtered = data.map(d=> {
return this.state.data.filter(item => item.uid !== d.uid);
}
this.setState({data: filtered});
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744893246a4599542.html
评论列表(0条)