【发布时间】:2025-12-11 10:30:01
【问题描述】:
我是 redux 的新手,因此试图找出身份验证用例的简单示例。此代码的 Web 版本从 localstorage 获取初始状态,并设置为 localstorage。将此示例转换为 react-native 意味着 localstorage 更改为异步的 AsyncStorage 并返回一个 Promise。
如何在 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;
}
};
【问题讨论】:
标签: javascript react-native redux react-redux