本文講解的是引用redux-saga後的路由跳轉問題。提供總共兩種方式javascript
1.首先安裝history和react-router-reduxjava
yarn add history react-router-reduxreact
2.在store裏面引用redux
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中應用react-router
import { push } from 'react-router-redux';
function* login() {
if (...) {// 登陸成功,路由跳轉
yield put(push('/'))
}
}
複製代碼
1.一樣須要安裝historyapp
yarn add historyide
2.封裝工具類history.js工具
import createHistory from 'history/createHashHistory'; //必定要注意分清楚createHashHistory和createBrowserHistory兩種路由方式的區別
export const history = createHistory()
複製代碼
3.主入口中引用ui
import { history } from '@/utils/history';
<HashRouter history={ history }> <Provider store={ store }> <App /> </Provider> </HashRouter>
複製代碼
4.sagaspa
import { history } from '@/utils/history';
function* login() {
if (...) {// 登陸成功,路由跳轉
yield put(history.replace('/'))
}
}
複製代碼