如何在reducer中处理异步promise

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在reducer中处理异步promise相关的知识,希望对你有一定的参考价值。

我是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;
  }
};
答案

创建一个动作创建器,用于从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。当你创建applyMiddleware时,请确保你store

中间件最常见的用例是支持异步操作,而不需要太多的样板代码或依赖于像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: '',
};

和减速器:

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

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

以上是关于如何在reducer中处理异步promise的主要内容,如果未能解决你的问题,请参考以下文章

在不用Promise的情况下如何控制异步请求?

如何在 Promise 之间异步传递数据?

如何在V8中优化JavaScript异步编程?

react常见面试题

Promise相关

如何在 Node.js 流回调中聚合从异步函数生成的 Promise?