首页 > 解决方案 > 等待 Dispatch Action 在组件外完成

问题描述

我有一个屏幕,用户可以从中选择一种测验,然后应该生成测验问题,应该在商店中更新 currentGameInformation,然后应该可以看到新屏幕。

由于调度动作是异步的,有时 currentGameInformation 没有更新,所以我的应用程序在进入下一页时会崩溃。我希望它等到它进入下一页以便信息可用。

按下按钮时,在我的组件中调用了一个名为 startTheGame() 的函数

//inside the screen component 
startTheGame = async (id) => {
    let navigation = this.props.navigation;
    await StartTheGame(MASTER_TIME_PERIOD, {time_period_id: id}).then(function(){
        console.log("Navigating");
        navigation.replace('Quiz');
    });

};


//This function is located outside the component,
//It is a library that handles all the Quiz functionalities
export async function StartTheGame(type, details) {
let state = store.getState();
let username = state.currentUser.username;
if(username === undefined){
   //AWS gets the current user working fine and waiting to be completed
   let user = await GetCurrentUserAWS(); 
   username = user.username;
}
//set game status to loading
let currentGameInfo = {};

let currentDayPoints = await GetCurrentDayPointsForUserDB(username); 

//Redux Thunk function (is sent, but not waiting to get done) 
SetCurrentDayPoints(currentDayPoints); 
//redux thunk function (is set but not waiting for it to be done) 
SetGameStatus(SET_GAME_START_LOADING, QUIZ_GAME_START_STATUS_LOADING); 
//at this point, current day points are either updated/not and same with game status

let questions = await GenerateQuestions(type, details).catch(err => {
    SetGameStatus(SET_GAME_START_ERROR, QUIZ_GAME_START_STATUS_ERROR); //same not waiting to be completed
});

currentGameInfo = {
    questions: questions,
    points: 0,
    questionIndexesAnsweredCorrectly: [],
    questionIndexesAnsweredIncorrectly: [],
    shouldRestartBeEnabled: false,
    currIndex:0,
    questionsAnsweredInRow:0,
    gameType:type
};
SetGameStatusSuccess(currentGameInfo); //same not waiting 
return currentGameInfo; }

我的目标是仅在 SetGameStatusSuccess 完成后返回

export function SetGameStatusSuccess(currentGameInfo){
return (dispatch, getState) => {
    dispatch({type: SET_GAME_START_SUCCESS, payload:{
            gameStatus:QUIZ_GAME_START_STATUS_STARTED,
            currentGameInformation:currentGameInfo
    }});
}; }

export function SetGameStatus(gameStatus, quizStatus){
return (dispatch, getState) => {
    dispatch({type: gameStatus, payload:{gameStatus:quizStatus}});
};}

我想知道是否有一种方法可以在不需要 mapDispatchToProps 函数的情况下做到这一点?

标签: reactjsreact-nativereduxreact-reduxredux-thunk

解决方案


你需要await你的SetGameStatus函数调用。由于您的StartTheGame功能被标记为异步,您需要做的就是:

let currentDayPoints = await GetCurrentDayPointsForUserDB(username); 
SetCurrentDayPoints(currentDayPoints); 
//add 'await' here
await SetGameStatus(SET_GAME_START_LOADING, QUIZ_GAME_START_STATUS_LOADING); 

和这里一样:

let questions = await GenerateQuestions(type, details).catch(asybc (err) => {
    await SetGameStatus(SET_GAME_START_ERROR, QUIZ_GAME_START_STATUS_ERROR);
});

推荐阅读