rxjs+react18.0+redux-observable+redux

入口文件:

import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

import { legacy_createStore as createStore, applyMiddleware } from 'redux'

import { createEpicMiddleware } from 'redux-observable';

import { Provider } from 'react-redux';

import rootReducer from './reducers/root'

import { rootEpic } from './epics'

const epicMiddleware = createEpicMiddleware();

function getStore() {

  const store = createStore(rootReducer, applyMiddleware(epicMiddleware))

  epicMiddleware.run(rootEpic)

  return store

}

const store = getStore()

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(

  <Provider store={store}>

    <App />

  </Provider>

);

2.请求必须也是一个观察者对象;

import * as Rx from 'rxjs'

import qs from 'qs'

import { ajax } from 'rxjs/ajax'

import { catchError, map } from 'rxjs/operators'

const baseUrl = "http://localhost:3008"

const request = (url, options) => {

    (!options.method) && (options.method = "GET")

    (!options.type) && (options.type = "urlencoded")

    if (options.type === 'urlencoded') {

        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };

        options.body = qs.stringify(options.body)

    }

    let URL = baseUrl + url

    if (options.hasOwnProperty('params')) {

        if (/^(GET|DELETE|HEAD|OPTIONS)$/i.test(options.method)) {

            const idQuest = URL.includes('?') ? "&" : "?"

            URL += `${idQuest}${qs.stringify(options.params)}`

        }

    }

    if (/^(POST|PUT)$/i.test(options.method)) {

        if (options.type === 'json') {

            options.headers = { 'Content-Type': 'application/json' };

            options.body = JSON.stringify(options.body)

        }

    }

    delete options.params//不支持parmas,需要从配置项删除

    let token = localStorage.getItem("token")

    token && (options.headers.Authorization = token)

    Object.assign(options, {

        credentials: 'include',

        url: URL,

        withCredentials: true,

        method: options.method,

        headers: options.headers,

        body: options.body,

        timeout: 300000,

        crossDomain: true,

        hasContent: true

    })

    return ajax({ ...options }).pipe(map(res => {//状态码这里处理

        if (res) {

            return res.response

        }

    }), catchError(error => {

            console.log('error: ', error);

            return Rx.of(error);

        }))

}


 

export default request

3.epics函数会被合并在combineEpics 中,

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值