react-redux中实现页面跳转

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
  • 初始化步骤

    1. 初始化history
import createHistory from 'history/createBrowserHistory';

const history = createHistory();
  1. 初始化中间件
import { routerMiddleware } from 'react-router-redux';

const historyMiddleware = routerMiddleware(history);
  1. 使用routerReducer
import { routerReducer } from "react-router-redux";
  1. 把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,
})
  1. 把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'));       
        }
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值