1
我是redux的新手,所以試圖找出一個認證用例的簡單示例。此代碼的Web版本從localstorage獲取初始狀態,並設置爲localstorage。將此示例轉換爲react-native意味着localstorage更改爲異步的AsyncStorage並返回承諾。如何處理reducer中的異步承諾
如何處理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;
}
};