Я пытался отделить управление своим состоянием в своем собственном приложении реагирования и пытался защитить свои маршруты с помощью аутентификации:
Мой Redux Store состоит из двух редукторов и комбинированных состояний:
redurs.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(),