如何解决返回的Ngrx存储值是true,但尝试访问它却给出了未定义的值
状态值根据reducer返回true或false,但无法访问未定义的状态。
这是我的组件代码:
getState : Observable<any>;
isAuthenticated : false;
user = null;
errorMessage = null;
constructor( private store : Store<AppState>) {
this.getState = this.store.select(selectAuthState);
}
ngOnInit(): void {
this.getState.subscribe((state)=>{
this.isAuthenticated = state.isAuthenticated;
this.user = state.user;
this.errorMessage = state.errorMessage;
});
}
state.ts代码:
export interface AppState{
authState : auth.State;
}
export const reducers = {
auth : auth.reducer
}
export const selectAuthState = createFeatureSelector<AppState>('auth');
减速器代码:
export interface State{
isAUthenticated : boolean;
user : User | null;
errorMessage : string | null;
}
export const initialState : State = {
isAUthenticated : false,user : null,errorMessage : null
}
export function reducer (state = initialState,action : All) : State{
switch(action.type){
case AuthActionTypes.LOGIN_SUCCESS : {
return{
...state,isAUthenticated:true,user:{
token : action.payload.token,email : action.payload.email
},errorMessage : null
};
}
case AuthActionTypes.LOGIN_FAILURE : {
return{
...state,errorMessage : 'Incorrect email and/or password'
};
}
case AuthActionTypes.SIGNUP_SUCCESS :{
return{
isAUthenticated : true,user:{
token:action.payload.token,email:action.payload.email
},errorMessage: null
};
}
case AuthActionTypes.SIGNUP_FAILURE : {
return{
...state,errorMessage : 'That email is already in use.'
};
}
case AuthActionTypes.LOGOUT : {
return initialState;
}
case AuthActionTypes.RESET :{
return initialState;
}
default : {
return state;
}
}
}
您可以看到返回的状态值为true,但是state.isAuthenticated未定义。我什至在状态值相应更改的redux devtools中查看了状态值。
解决方法
您输入的错字是“ isAUthenticed”和“ isAuthenticated”
case AuthActionTypes.SIGNUP_SUCCESS :{
return{
isAUthenticated : true,user:{
token:action.payload.token,email:action.payload.email
},errorMessage: null
};
}
您的调试消息也显示此错字
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。