我正在使用带有redux的react native来构建移动应用程序。当用户杀死该应用程序并随后又返回该应用程序时,我希望他结束在他之前离开的页面上,并且如果他的令牌仍然有效,则不进行登录过程。
这是我设置商店的方式:
import { createStore, compose, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import reducers from '../reducers';
import { persistStore, autoRehydrate, persistReducer } from 'redux-persist';
import { AsyncStorage } from 'react-native';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import axios from 'axios';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
stateReconciler: autoMergeLevel2,// see "Merge Process" section for details.
blacklist: ['error', 'loading', 'backgroundImage']
};
const pReducer = persistReducer(persistConfig, reducers);
export const store = createStore(
pReducer,
{},
compose(
applyMiddleware(ReduxThunk)
)
);
export const persistor = persistStore(store);
这是我的App组件:
import { persistor, store } from './src/store'
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<PersistGate persistor={persistor}>
<Router />
</PersistGate>
</Provider>
);
}
}
我决定要做的是检查路由器中的补水状态,并相应地设置我的初始视图。
这是我的场景:
<Scene key='chrono' hideNavBar component={Starter} initial={ this.props.initialPage == 'chrono' }/>
<Scene key='time' hideNavBar title='TIME' component={TimeCardList} icon={ChronoIcon} initial={ this.props.initialPage == 'time'}/>
<Scene key='client' hideNavBar title='CLIENT' component={ClientList} icon={TabIcon} initial={ this.props.initialPage == 'client'}/>
<Scene key='projects' hideNavBar title='PROJECT' component={ProjectList} icon={TabIcon} initial={ this.props.initialPage == 'projects'}/>
<Scene key='info' hideNavBar title='INFO' component={Info} icon={TabIcon} initial={ this.props.initialPage == 'info'}/>
这是路由器中mapStateToProps中发生的事情:
let initialPage = 'login'
if (state._persist){
if (state._persist.rehydrated && state.authentication.token){
API.defaults.headers.common['Authorization'] = 'Bearer ' + state.authentication.token;
console.log('fu')
initialPage = state.tabs.activeTab
}
}
return {
initialPage: initialPage
}
它可以工作,但是在我看来这是一个非常糟糕的模式,因为我想在应用程序重新启动时仅用一次auth令牌设置我的授权标头。 您将如何以更正确的方式实现这一目标?