在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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章