入口文件:
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 中,