connected-react-router

此库可以让redux中完成路由跳转相关的功能

  • 安装此库
yarn add connected-react-router

安装配置使用分为三步走

第一步

💖在入口文件中把原来的react-router-dom中定义路由模式组件更换,注意添加上这个history属性,并在src的同级目录下添加一个history.js文件。

// history模块它是react-router-dom安装成功后就存在的,无需手动再安装
import { createBrowserHistory, createHashHistory } from 'history'
const history = createBrowserHistory()
// 告知当前路由的模式为 history模式
export default

index.js

import { ConnectedRouter as Router } from 'connected-react-router'
import history from './history';
import App from './App';


ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById('root')
)

第二步

💝在reducer模块化中(总出口),定义一个router的模块

import { combineReducers} from "redux"

import user from "./user"
import count from "./count"

import { connectRouter } from 'connected-react-router'
import history from '@/history'

export default combineReducers({
// 添加一个reducer的模块
router: connectRouter(history),
user,
count
})

第三步

💥在redux入口文件中,以中间件的方式把connected-react-router包含到redux中;

import { createStore,applyMiddleware } from "redux";
import { composeWithDevTools } from '@redux-devtools/extension'
import reducer from "@/store/reducer/index"

//saga
import mainSaga from "./sagas";
import createSagaMiddleware from "redux-saga";

// redux中路由
import { routerMiddleware } from 'connected-react-router'
import history from '@/history'

const SagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(SagaMiddleware,routerMiddleware(history)))
)

// 运行saga
SagaMiddleware.run(mainSaga)
// 导出store
export default

connected-react-router使用

导入push,使用push来跳转到指定的路由,通过put来完成push使用。

通过库,可以完成在redux中实现跳转功能
import { push,replace,goBack } from "connected-react-router"
import {takeEvery,put,call} from "redux-saga/effects"
function delay(n=2){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve({code:200,data:"ok"})
},1000*n)
})
}

function* watchSaga() {
yield takeEvery('asyncadd', addSaga)
}

/* 工作saga在此处完成网络请求 */
function* addSaga({payload}) {
/*收到发过的的dispatch */
let ret = yield call(delay,1)
console.log(ret);
if(ret.code == 200){
yield put({type:"loginadd",payload:{data:ret.data}})//全局更新登录信息
// 跳转到某一个路由
yield put(push("/home/index"))
}
export default