react-redux中实现页面跳转
由于react-router版本变化,网上好些资料跑步起来。
当前使用版本如下:
"react-router": "^4.0.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^5.0.0-alpha.9",
- 安装
npm install --save react-router-redux@next
npm install --save history
初始化步骤
- 初始化history
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
- 初始化中间件
import { routerMiddleware } from 'react-router-redux';
const historyMiddleware = routerMiddleware(history);
- 使用routerReducer
import { routerReducer } from "react-router-redux";
- 把historyMiddleware和routerReducer加入到redux的初始化流程中
const middlewares = process.env.NODE_ENV === 'development' ?
[ applyMiddleware(createLogger()), applyMiddleware(promiseMiddleware),applyMiddleware(historyMiddleware), DevTools.instrument()] :
[ applyMiddleware(createLogger()), applyMiddleware(promiseMiddleware),applyMiddleware(historyMiddleware),];
const appReducer = combineReducers({
authentication,
user,
routerReducer,
})
- 把history到路由中
import { ConnectedRouter } from "react-router-redux";
import {history} from "config/store";
<ConnectedRouter history={history}>
...
</ConnectedRouter>
- 实现跳转
跳转比较方便,使用dispatch(push(path))
,比如登录后的跳转
import {push} from 'react-router-redux';
afterSuccess: (dispatch, getState, response) => {
console.log("login success", response);
localStorage.setItem('auth-token', response.data.access_token);
dispatch(push('/user'));
}