正确获取Redux Store

时间:2018-07-16 00:10:41

标签: react-native redux axios react-navigation redux-thunk

我需要获得商店才能将令牌传递给我的标头。

我将商店导入到我的api util中并在那里订阅。然后在该侦听器函数中,使用新获取的令牌设置axios的全局默认值。

实现这一目标的最佳方法是什么?

Store.js

const config = {
   key: 'root',
   storage,
   whitelist: ['auth']
};

const pReducer = persistReducer(config, reducers);
const enhancers = [applyMiddleware(middleware, thunk)];
const persistConfig = { enhancers };
export const store = createStore(pReducer, {}, compose(...enhancers));
console.log(store.getState()); // It works!

const persistor = persistStore(store, persistConfig, () => {
   // console.log(store.getState());
});

const configureStore = () => ({ persistor, store });

export default configureStore;

Axios.js

import { store } from './store';
console.log(store.getState()); // Not working

navigationStack.js

const RootNavigator = createStackNavigator({
    Login: { screen: LoginStack },   // createStackNavigator
    Main: { screen: Drawer }  // createDrawerNavigator
}, {
    headerMode: 'none',
    header: { visible: false },
});

export default RootNavigator;

navReducer.js

import { StackActions, NavigationActions } from 'react-navigation';
import RootNavigator from '../Routes/navigationStack';
import {
    MAIN_SCREEN
} from '../Actions/actionTypes';

const firstAction = RootNavigator.router.getActionForPathAndParams('Login');   // Line 11
const initialNavState = RootNavigator.router.getStateForAction(firstAction);

export default (state = initialNavState, action) => {
    let nextState;
    switch (action.type) {
        case MAIN_SCREEN:
            nextState = RootNavigator.router.getStateForAction(
                StackActions.reset({
                    index: 0,
                    actions: [NavigationActions.navigate({ routeName: 'Main' })]
                }), state
            );
            break;
        default:
            nextState = RootNavigator.router.getStateForAction(action, state);
            break;
    }

    return nextState || state;
};

Given error

0 个答案:

没有答案