[英]Add callback to function that is called from inside arr map method
我需要映射我的状态中的数组并将返回的值分配给我的状态中的另一个属性。 然后,我需要使用updated属性的值作为参数调用函数,等待此函数完成,然后在重复该过程之前继续到我的数组映射方法中的下一个项目。
问题是我认为我的函数是在我的arr.map方法的每次迭代更新状态之前运行的。
我想我需要在运行我的函数之前使用componentDidUpdate()方法,但我不确定如何在这种情况下实现它。
通过代码示例更容易解释,请参见下文(为简单起见而编辑):
state = {
a: [ {name: 'some string'}, {name: 'some string'}..... ],
b: '' // empty string
}
// when button is clicked, this function is run
myFunc() {
this.state.a.map( (item) => {
this.setState({
b: item.name
})
mySecondFunc()// perform next part of the loop
})
}
mySecondFunc() {
alert( this.state.b )
}
mySecondFunc()中的警报不返回任何内容,在运行该函数之前未进行更新。 我需要做的是,地图将从我的状态'a'数组中获取第一个项目,将其分配给状态'b'并运行mySecondFunc()。 我需要等待状态更新,然后再调用mySecondFunc,然后等待mySecondFunc()结束其功能,然后地图从我的状态'a'数组中获取下一个项目并再次调用mySecondFunc。
这是我无法弄清楚的部分。
尝试这个
state = {
a: [ {name: 'some string'}, {name: 'some string'}..... ],
b: '' // empty string
}
// when button is clicked, this function is run
myFunc(){
this.state.a.map(async(item) => {
await this.setState({
b: item.name
},async () => {
await mySecondFunc()// perform next part of the loop
})
})
}
mySecondFunc() {
alert( this.state.b )
}
//OR
myFunc(){
this.state.a.map(async(item) => {
await mySecondFunc(item)
})
}
mySecondFunc(item) {
alert( item )
}
我从问题描述中理解的是,这里的目标是将b的值顺序传递给mySecondFunc。 根据我对问题的理解,我修改了你的代码:
myFunc() {
this.state.a.map( (item) => {
this.setState( (prevState) => {
const modifiedName = item.name;
this.mySecondFunc(modifiedName);
return {
b: modifiedName
}
});
});
}
mySecondFunc(name) {
alert( name );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.