我一直试图在我的本地应用程序中分离状态管理,并尝试通过身份验证来保护路由:
我的Redux Store由两个reducer和一个组合状态组成:
reducers.js:
...
const reducers = combineReducers({
auth:authReducer,
position: positionReducer,
})
export default reducers;
AuthReducer.js:
import * as Types from '../actions/types';
export const defaultState = {
isAuthenticated: false,
user: {
username: null,
email: null,
phoneNumber: null,
uid: null,
photoURL: null
},
authError: ''
}
module.exports = (state = defaultState, action) => {
switch (action.type) {
case Types.LOGIN_SUCCESS: {
var userObj = {
username: null,
uid: action.response.user.uid,
email: action.response.user.email,
phoneNumber: null,
photoURL: null,
}
}
return {
...state,
authError: '',
user: userObj,
isAuthenticated: true,
}
case Types.LOGIN_FAILURE:
return {
...state,
authError: action.error.message,
isAuthenticated: false,
};
case Types.SIGN_IN_SUCCESS:
return {
...state,
user: {
uid: action.response.user.uid,
email: action.response.user.email
}
}
case Types.SIGN_IN_FAILURE:
return {
...state,
authError: action.error.message
}
case Types.LOGOUT_SUCCESS:
return {
...state,
isAuthenticated: true,
}
case Types.LOGOUT_FAILURE:
return {
...state,
isAuthenticated: false,
}
default:
return state;
}
}
Store.js:
import { createStore, compose,applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import reducers from '../reducers';
import authState from '../reducers/authReducer';
import positionState from '../reducers/positionReducer';
defaultState = {
auth: authState,
position: positionState
}
export const configureStore = (initialState = defaultState , action) => {
var store = createStore(
reducers,
initialState,
compose(autoRehydrate(), applyMiddleware(thunk)));
//AsyncStorage.clear();
persistStore(store, {storage: AsyncStorage });
return store;
}
我的navigation.js就像这样:
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: LoadingStack,
App: MainStack,
Auth: authStack,
},
{
initialRouteName: 'AuthLoading',
}
));
在AuthLoading.js中,同时记录变量state.auth.isAuthenticated,结果是未定义,我使用Reactotron进行检查,得到:
auth: fn(),
position: fn(),