React 等待一个循环(和 setState)在另一个循环之前完成

handleSubmit = () => {

    this.setState({ modalState: false })


    this.state.codeToClass.forEach((code, classId, map) => {

      const cr = _.find(this.state.classRoles, { id: classId })


      if (code === cr.classCode) {

        console.log('here')

        this.setState(state => ({ 

          classRoles: state.classRoles.map((cc) => {

            console.log(cc.id)

            console.log(classId)

            console.log(cc.id === classId)

            if (cc.id === classId) {

              console.log('here1')

              return {

                ...cc,

                role: 'TA',

              }

            }

            console.log('what')

            return cc

          }),

        }), ()=> console.log(this.state.classRoles)) //this is called later

        

      } else {

        NotificationManager.error('Failed to register as TA.')

      }

    })

    console.log(this.state.classRoles) //this is called first

    this.state.classRoles.forEach((c) => {

      if (c.role === '') {

        api.deleteClassUser(c.id, this.state.user.id)

      } else {

        api.postAddClass(c.id, this.state.user.id, c.role)

        console.log(c)

      }

    })


    EventEmitter.publish('currentlyEnrolled', this.state.classRoles)

  }

我正在尝试在第一个 forEach 完成后运行第二个 forEach,即状态已更新。但它一直按这个顺序运行。有没有办法来解决这个问题?


侃侃无极
浏览 277回答 3
3回答

largeQ

this.setState 是一个异步操作。你可以尝试这样的事情:handleSubmit = () => {   //some code...      this.setState(state => ({      state.codeToClass.forEach((...args) => {         //logic to update the state...      });   }), setClassRoles); //call a function after the state value has updated   }setClassRoles = () => {    this.state.classRoles.forEach((...args) => {        //your code...    });    EventEmitter.publish('currentlyEnrolled', this.state.classRoles)}

慕妹3146593

有两种选择。使用承诺异步等待由于地图可以与等待一起使用,我认为const tempState = this.state.codeToclass; await tempState.map(...这种方式可以工作:)

互换的青春

Promise是你的朋友。// You map your operations in to Promises. const promises = this.state.codeToClass.map((code, classId, map) => {   return new Promise(resolve=>{      const cr = _.find(this.state.classRoles, { id: classId })      if (code === cr.classCode) {        console.log('here')        this.setState(state => ({           classRoles: state.classRoles.map((cc) => {            console.log(cc.id)            console.log(classId)            console.log(cc.id === classId)            if (cc.id === classId) {              console.log('here1')              return {                ...cc,                role: 'TA',              }            }            console.log('what')            return cc          }),        }), ()=> resolve()) //this is called later              } else {        NotificationManager.error('Failed to register as TA.')      }    })})// and then you wait for all of the promisesawait Promise.All(promises);// then continue to execution
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript