wno*_*eno 3 reactjs react-jsx react-router react-redux
我创建了一个中间件来检查请求是否返回无效的访问响应.如果状态是401,我想将用户重定向到登录页面
这是中间件代码
import React from 'react';
import { push, replace } from 'react-router-redux';
const auth_check = ({ getState }) => {
return (next) => (action) => {
if(action.payload != undefined && action.payload.status==401){
push('login');
console.log('session expired');
}
// Call the next dispatch method in the middleware chain.
let returnValue = next(action);
return returnValue
}
}
export default auth_check;
Run Code Online (Sandbox Code Playgroud)
将它包含在index.js中
...
const store = createStore(reducers, undefined,
compose(
applyMiddleware(promise,auth_check)
)
);
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
, document.querySelector('.app'));
Run Code Online (Sandbox Code Playgroud)
push方法不会重定向页面.我确信代码会在日志显示后通过该部分
如果您更喜欢Redux样式操作,则库还提供一组操作创建器和中间件来捕获它们并将它们重定向到您的历史记录实例.
对于: push(location), replace(location), go(number), goBack(), goForward()
您必须安装routerMiddleware才能使这些动作创建者工作.
import { routerMiddleware, push } from 'react-router-redux'
// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
reducers,
applyMiddleware(middleware)
)
// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))
Run Code Online (Sandbox Code Playgroud)
React Router还提供了单例版本的历史记录(browserHistory和hashHistory),您可以从应用程序的任何位置导入和使用它们.
import { browserHistory } from 'react-router'
if(action.payload != undefined && action.payload.status==401){
browserHistory.push('login');
console.log('session expired');
}
Run Code Online (Sandbox Code Playgroud)
btw for check auth你可以使用onEnter或redux-auth-wrapper
| 归档时间: |
|
| 查看次数: |
7429 次 |
| 最近记录: |