3 回答

TA貢獻2039條經驗 獲得超8個贊
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)
}

TA貢獻1820條經驗 獲得超9個贊
有兩種選擇。
使用承諾
異步等待
由于地圖可以與等待一起使用,我認為
const tempState = this.state.codeToclass; await tempState.map(...
這種方式可以工作:)

TA貢獻1797條經驗 獲得超6個贊
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 promises
await Promise.All(promises);
// then continue to execution
添加回答
舉報