react中——connected-react-router的使用

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 history

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 store

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 watchSaga

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢*牛牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值