乐趣区

在redux中使用reactrouterredux-跳转路由

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);
    }
}
退出移动版