首页 > 解决方案 > 当我在反应本机 redux 中更新状态时,会删除以前的状态

问题描述

登录后我在应用程序内调用 get_user_profile_api 。成功登录后,我的应用程序的状态为用户和令牌。但是一旦调用了 GET_USER_PROFILE_SUCCESS,状态就只剩下 userData 和 isLoading。用户和令牌从状态中删除。

import { CONST } from '../../utils/Const';
import * as types from './types';

const initialState = {
  isLoading: false,
  user: null,
  userData: null,
  isLoggedIn: false,
  token: '',
};

export default authReducer = (state = initialState, action) => {
  console.log('action :: ', action);
  switch (action.type) {
    case types.GET_USER_PROFILE_LOADING:
    case types.LOGIN_LOADING:
      return {
        isLoading: true,
      };

    case types.GET_USER_PROFILE_SUCCESS:
      return {
        ...state,
        isLoading: false,
        userData: action.payload,
      };

    case types.LOGIN_SUCCESS:
      return {
        ...state,
        isLoading: false,
        isLoggedIn: true,
        user: action.payload.user,
        token: action.payload.token,
      };

    case types.LOGIN_ERROR:
    case types.GET_USER_PROFILE_ERROR:
      return {
        ...state,
        isLoading: false,
      };

    default:
      return {
        ...state,
        isLoading: false,
      };
  }
};

标签: javascriptreact-nativereact-redux

解决方案


这段代码没有任何问题,我认为问题在于您从哪里调用这些操作,如果有令牌,或者您没有将状态正确映射到道具,您可以在使用效果挂钩中调用它们以获取用户配置文件


推荐阅读