如何在reducer

时间:2016-11-20 14:23:49

标签: javascript react-native redux react-redux

我是redux的新手,所以试图弄清楚身份验证用例的简单示例。此代码的Web版本从localstorage获取初始状态,并设置为localstorage。将此示例转换为react-native意味着localstorage更改为异步并返回promise的AsyncStorage。

如何在reducer中处理异步初始值设定项?

import { AsyncStorage } from 'react-native';
import {
  LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_SUCCESS,
} from '../actions/login';


const initialState = {
  isFetching: false,
  token: null, // AsyncStorage.getItem('token'),
  profile: null, // AsyncStorage.getItem('profile'),
  isLoggedIn: false,
  errorMessage: null,
};

// The auth reducer. The starting state sets authentication
// based on a token in asyncstorage. In addition we would also null
// the token if we check that it's expired
export default (state = initialState, action) => {
  switch (action.type) {
    case LOGIN_REQUEST:
      return Object.assign({}, state, {
        isFetching: true,
        isLoggedIn: false,
        token: null,
        user: null,
        errorMessage: '',
      });
    case LOGIN_SUCCESS:
      // todo set the async
      // AsyncStorage.multiSet(['token', 'profile'], [action.token, action.profile])
      return Object.assign({}, state, {
        isFetching: false,
        isLoggedIn: true,
        token: action.token,
        user: action.profile,
        errorMessage: '',
      });
    case LOGIN_FAILURE:
      return Object.assign({}, state, {
        isFetching: false,
        isLoggedIn: false,
        token: null,
        errorMessage: action.message,
      });
    case LOGOUT_SUCCESS:
      // AsyncStorage.multiRemove(['token', 'profile'])
      return Object.assign({}, state, {
        isFetching: true,
        isLoggedIn: false,
        token: null,
      });
    default:
      return state;
  }
};

1 个答案:

答案 0 :(得分:1)

创建操作创建者,以便从AsyncStorage中获取初始数据。当您的应用加载时,您可以使用密钥tokenprofile来发送操作(您可以在根组件的componentDidMount中执行此操作)。

// create similar actions creators for 'setItem' and 'multiSet' ops
export function loadLocalData(key) {
  return {
    types: [LOAD_LOCAL_DATA, LOAD_LOCAL_DATA_SUCCESS, LOAD_LOCAL_DATA_FAIL]
    asyncStoragePromise: () => AsyncStorage.getItem(key),
    key,
  }
}

现在为AsyncStorage操作创建middleware。创建store时确保applyMiddleware

  

中间件最常见的用例是支持异步   没有太多样板代码或对库的依赖的动作   像Rx。它通过让您再发送异步操作来实现   正常行动。

export default function asyncStorageMiddleware() {
  return ({ dispatch, getState }) => next => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState);
    }

    const { asyncStoragePromise, types, ...rest } = action;

    if (!asyncStoragePromise) {
      return next(action);
    }

    const [REQUEST, SUCCESS, FAILURE] = types;

    next({ ...rest, type: REQUEST });

    const actionPromise = asyncStoragePromise();
    actionPromise
      .then(result => next({ ...rest, result, type: SUCCESS }))
      .catch(error => next({ ...rest, error, type: FAILURE }));

    return actionPromise;
  };
}

最后这是 initialState

const initialState = {
  isFetching: false,
  token: null,
  profile: null,
  isLoggedIn: false,
  errorMessage: null,
  localLoadErr: '',
};

redurs

LOAD_LOCAL_DATA_SUCCESS:
  return {
    ...state,
    [action.key]: action.result,
  };
  break;

LOAD_LOCAL_DATA_FAIL:
  return {
    ...state,
    localLoadErr: action.error,
  };
  break;