1

我使用react-thunkwithredux来实现登录功能,但是当我使用 访问状态时getState(),该属性返回未定义。

SystemState将设置IsLogineduser何时LoginSuccessed,我稍后将使用它作为访问令牌。但是当我尝试实现注销功能时,getState().Property返回 undefined

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

组合减速机

const rootReducer = combineReducers({
    systemState
});
4

1 回答 1

0

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

您已将根减速器定义为:

const rootReducer = combineReducers({
    systemState
});

反过来systemState,reducer 的初始状态为:

const initState = {    
    isLogined: false
}

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

{
    systemState : {
        isLogined : true
    }
}

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

因此,就您而言,您可能想要的是:

const state = getState();
const {isLogined} = state.systemState;
于 2019-04-10T08:45:26.803 回答