react redux-saga 路由跳转

2,397 阅读1分钟

本文讲解的是引用redux-saga后的路由跳转问题。提供总共两种方式

一、react-router-redux

1.首先安装history和react-router-redux

yarn add history react-router-redux

2.在store里面引用

import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import reducer from './reducers';
import sagas from './sagas'
import { routerMiddleware } from 'react-router-redux';

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

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware, routerWare));
const store = createStore(
    reducer,
    enhancer
)

sagaMiddleware.run(sagas)

export default store

3.在saga中应用

import { push } from 'react-router-redux';
function* login() {
  if (...) {// 登录成功,路由跳转
    yield put(push('/'))
  }
}

二、createHistory

1.同样需要安装history

yarn add history

2.封装工具类history.js

import createHistory from 'history/createHashHistory'; //一定要注意分清楚createHashHistory和createBrowserHistory两种路由方式的区别

export const history = createHistory()

3.主入口中引用

import { history } from '@/utils/history';

<HashRouter history={ history }>
    <Provider store={ store }>
        <App />
    </Provider>
</HashRouter>

4.saga

import { history } from '@/utils/history';

function* login() {
  if (...) {// 登录成功,路由跳转
    yield put(history.replace('/'))
  }
}