我使用react-thunkwithredux来实现登录功能,但是当我使用 访问状态时getState(),该属性返回未定义。
SystemState将设置IsLogined和user何时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
});