【问题标题】:getState().property return undefined inside an async functiongetState().property 在异步函数中返回 undefined
【发布时间】:2019-08-30 14:47:27
【问题描述】:

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

SystemState 会在LoginSuccessed 时设置IsLogineduser,稍后我将使用它作为访问令牌。但是当我尝试实现注销功能时,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
});

【问题讨论】:

  • 你能展示你剩下的减速器吗?你的combineReducers() 电话是什么样的?
  • 嗨@mar​​kerikson,我已经添加了reducer和combineReducers(),但它似乎与我的问题无关。

标签: reactjs react-redux react-thunk


【解决方案1】:

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

您已将根减速器定义为:

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;

【讨论】:

  • 谢谢。我根据你的建议更新了我的代码,结果我的ThunkAction 没有使用正确的StateStore,应该使用全局的AppStateStore,而不是单独的SystemState
猜你喜欢
  • 2018-07-09
  • 2020-10-23
  • 2018-09-15
  • 2019-01-27
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多