我有来自服务器的令牌身份验证,所以当我的Redux应用程序最初加载时,我需要向该服务器发出请求,以判断用户是否经过身份验证,如果是,我应该获得令牌.
我发现不建议使用Redux core INIT操作,所以在呈现应用程序之前,我如何调度操作?
我有来自服务器的令牌身份验证,所以当我的Redux应用程序最初加载时,我需要向该服务器发出请求,以判断用户是否经过身份验证,如果是,我应该获得令牌.
我发现不建议使用Redux core INIT操作,所以在呈现应用程序之前,我如何调度操作?
Update 2020:
export default () => next => action => {
const result = next(action);
const { type, payload } = result;
if (type.endsWith('Failure')) {
if (payload.status === 401) {
removeToken();
window.location.replace('/login');
}
}
return result;
};
Update 2018:这个答案适用于React Router 3
我用onEnter个props 解决了这个问题.下面是代码的样子:
// this function is called only once, before application initially starts to render react-route and any of its related DOM elements
// it can be used to add init config settings to the application
function onAppInit(dispatch) {
return (nextState, replace, callback) => {
dispatch(performTokenRequest())
.then(() => {
// callback is like a "next" function, app initialization is stopped until it is called.
callback();
});
};
}
const App = () => (
<Provider store={store}>
<IntlProvider locale={language} messages={messages}>
<div>
<Router history={history}>
<Route path="/" component={MainLayout} onEnter={onAppInit(store.dispatch)}>
<IndexRoute component={HomePage} />
<Route path="about" component={AboutPage} />
</Route>
</Router>
</div>
</IntlProvider>
</Provider>
);