[英]Add callback to function that is called from inside arr map method
I need to map over an array in my state and assign the returned value to another property in my state. 我需要映射我的状态中的数组并将返回的值分配给我的状态中的另一个属性。 I then need to call a function using the value of the updated property as a parameter, wait for this function to complete and then move on to the next item in my array map method before repeating the process. 然后,我需要使用updated属性的值作为参数调用函数,等待此函数完成,然后在重复该过程之前继续到我的数组映射方法中的下一个项目。
The problem is that I think my function is being run before the state has been updated through each iteration of my arr.map method. 问题是我认为我的函数是在我的arr.map方法的每次迭代更新状态之前运行的。
I think I need to utilise the componentDidUpdate() method before running my function, but I am not sure how to implement that in this scenario. 我想我需要在运行我的函数之前使用componentDidUpdate()方法,但我不确定如何在这种情况下实现它。
Simpler to explain through code example, see below (edited for simplicity): 通过代码示例更容易解释,请参见下文(为简单起见而编辑):
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 )
}
The alert in mySecondFunc() does not return anything, it is not being updated before the function is run. mySecondFunc()中的警报不返回任何内容,在运行该函数之前未进行更新。 What I need to happen is that the map will get the first item from my states 'a' array, assign it to state 'b' and run mySecondFunc(). 我需要做的是,地图将从我的状态'a'数组中获取第一个项目,将其分配给状态'b'并运行mySecondFunc()。 I need to wait for state to be updated, before calling mySecondFunc, and then wait for mySecondFunc() to end its function before the map gets the next item from my state's 'a' array and calls mySecondFunc again. 我需要等待状态更新,然后再调用mySecondFunc,然后等待mySecondFunc()结束其功能,然后地图从我的状态'a'数组中获取下一个项目并再次调用mySecondFunc。
This is the part that I cannot figure out. 这是我无法弄清楚的部分。
try this 尝试这个
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 )
}
What I have understood from the problem description is that the goal here is to pass b's value sequentially to mySecondFunc . 我从问题描述中理解的是,这里的目标是将b的值顺序传递给mySecondFunc。 According to my understanding of the problem, I have modified your code : 根据我对问题的理解,我修改了你的代码:
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.