更新初始状态后,Redux状态未更改

时间:2019-12-12 08:43:47

标签: react-native redux react-redux

我有一个具有redux和auth状态以及reducer的React Native应用

s =

   10   26   42
   58   74   90

最初authState的初始状态为:

const authState = {
    token: 'sample-token',
    id: undefined,
    username: undefined,
    email: undefined,
    mobile: undefined
}

const authReducer = (state=authState, action) =>{
    switch(action.type){
        case "LOGIN":            
            state = {
                ...state, token: action.payload.token,
                id: action.payload.id, username: action.payload.username,
                email: action.payload.email, mobile: action.payload.mobile
            };
            break;         
        case "LOGOUT":
            state = {
                token: '', id: '', username: '', email: '', mobile: ''
            };
            break;        
    }
    return state;
}

export {authReducer};

但是,每当我在任何视图中执行console.log(this.props.auth)时,我都会得到旧状态的输出,而不是具有新数据的状态。

const authState = {
    token: '',
    id: '',
    username: '',
    email: '',
    mobile: ''
}

3 个答案:

答案 0 :(得分:0)

我认为您没有正确导出authReducer函数,并且在switch语句中没有正确返回状态。 试试下面的功能,

    const authReducer = (state=authState, action) =>{
        switch(action.type){
            case "LOGIN":            
                return {
                    ...state, token: action.payload.token,
                    id: action.payload.id, username: action.payload.username,
                    email: action.payload.email, mobile: action.payload.mobile
                };         
            case "LOGOUT":
                return {
                    token: '', id: '', username: '', email: '', mobile: ''
                };
           default:
               return state;    
        }
    }

export default authReducer;

答案 1 :(得分:0)

您确定要为相应的动作类型分派动作吗? 如果没有,请执行以下操作

export const login = () => {
  return {
    type: LOGIN,
    payload: { id: 1, username:'bla bla' }
  }
}

并在您的视图中导入动作并分派

const mapDispatchToProps = dispatch => {
    return {
        onLogin : () =>
            dispatch(login())
      }
  }

并这样称呼它。props.onLogin()

答案 2 :(得分:0)

我通过在switch语句中添加默认大小写来解决了我的问题。显然,如果我不添加默认案例,它将返回最后一个案例的状态。