我是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获取初始数据。当您的应用程序加载时,您可以使用密钥token
或profile
发送操作(您可以在根组件的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;