首页 > 解决方案 > 更新初始状态后 Redux 状态未更改

问题描述

我有一个带有 redux 和 auth state 和 reducer 的 react native 应用程序

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

最初的 authState 初始状态是:

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

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

console.log(this.props.auth)
Output: token: "", id: "", username: "", email: "", mobile: ""}

标签: react-nativereduxreact-redux

解决方案


我认为您没有正确导出 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;

推荐阅读