简体   繁体   中英

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.

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.

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.

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. 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(). 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.

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 . 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 );
}

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.

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