在redux中使用react-router-redux 跳转路由

1.安装

npm install --save history
npm install --save react-router-redux

2.封装

import {createStore, compose, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
import {routerMiddleware} from 'react-router-redux';

let createHistory = require('history').createHashHistory;
let history = createHistory();   // 初始化history
let routerWare = routerMiddleware(history);

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
    applyMiddleware(thunk, routerWare)
));

export default store;

3.使用

import {push} from 'react-router-redux';

// 任意一个actionCreators.js文件
// 登录
export const loginSystem = (params) => async (dispatch) => {
    try {
        dispatch(changeLoading(true));
        let {data} = await loginAsync(params); 
        if (data['msgCode'] === 0) {
            dispatch(changeUserName(true, params['username'])); 
            dispatch(push('/home')); // 跳转到home页面,其它都是示例代码,可忽略
        } else {
            Toast.info(data['message'], 2);
        }
        dispatch(changeLoading(false));
    } catch (error) {
        Toast.info(error, 2);
    }
}

相关推荐