getState()。property在异步函数中返回未定义的

时间:2019-04-09 10:24:47

标签: reactjs react-redux react-thunk

我将react-thunkredux结合使用以实现登录功能,但是当我使用getState()访问状态时,该属性返回undefined。

SystemState将在IsLogined时设置userLoginSuccessed,稍后我将使用它作为访问令牌。但是当我尝试实现注销功能时,getState().Property返回未定义

function logout() : ThunkAction<void, SystemState, null, Action<string>> {
    return async (dispatch, getState) => {
        const { user, isLogined } = getState();

        console.log(`user: ${user} isLogined:${isLogined}` )
        // Console writes user: undefined isLogined: undefined

        if (!isLogined) {
            dispatch(actions.LogoutFailed("No login Session Found"));
        } else if (user) {
            const result = await services.Logout(user.UserId);

            if (result.errorMessage) {
                dispatch(actions.LogoutFailed(result.errorMessage));
            } else {
                dispatch(actions.Logout());
            }
        }
    }
}

getState()是否不应在异步函数中调用?

---编辑---

SystemSate的减速器

const initState = {    
    isLogined: false
}

function SystemStateReducer(state = initState, action) {
    switch(action.type) {
        case types.LOGIN_SUCCESS:            
            return {
                ...state,
                isLogined: true, 
                user: action.user, 
                errorMessage: undefined
            }
        case types.LOGIN_FAILED:
            return {
                ...state, 
                isLogined: false, 
                user: undefined, 
                errorMessage: action.errorMessage
            }
        case types.LOGOUT_SUCCESS:
            return {
                ...state,
                isLogined: false, 
                user: undefined, 
                errorMessage: undefined
            }
        case types.LOGOUT_FAILED:
            return {
                ...state,                 
                isLogined: false, 
                user: undefined,
                errorMessage: action.errorMessage
            }
        default:
            return state;
    }
}

CombineReducer

const rootReducer = combineReducers({
    systemState
});

1 个答案:

答案 0 :(得分:0)

问题是您误解了状态结构。

您已将根减速器定义为:

const rootReducer = combineReducers({
    systemState
});

systemState减速器的初始状态为:

const initState = {    
    isLogined: false
}

这两件事定义了getState()返回的内容的结构,实际上是:

{
    systemState : {
        isLogined : true
    }
}

请注意,这意味着您需要state.systemState.isLogined,而不是state.isLogined

因此,在您的情况下,您可能想要的是:

const state = getState();
const {isLogined} = state.systemState;