Open gaowei1012 opened 3 years ago
添加 axios
模块
import axios from 'axios'
import { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'
import * as NProgress from 'nprogress'
import * as Cookies from 'js-cookie';
import { message } from 'antd'
import constant from './api';
const { dev_base_url } = constant
axios.defaults.timeout = 10000
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ?
'prod_base_url' : 'dev_base_url'
let startFlag: Boolean = false // loading start
export default function AxiosConfig() {
// 请求拦截器
axios.interceptors.request.use((config: AxiosRequestConfig) => {
if (config.data && config.data.showLoading) {
startFlag = true
NProgress.start()
}
// 添加请求 access_token
if (Cookies.get('auth')) {
config.headers.Authorization = Cookies.get('auth')
}
if (config.params) config.params._t = Date.now()
return config
}, (err: AxiosError) => {
if (startFlag) {
startFlag = false
NProgress.done()
}
return Promise.reject(err)
})
// 响应拦截
axios.interceptors.response.use((res: AxiosResponse) => {
if (startFlag) {
startFlag = false
NProgress.done()
}
return res.data
}, (err: AxiosError) => {
if (err.response && (err.response.status + '').startsWith('5')) {
message.error('请求出错!')
}
if (startFlag) {
startFlag = false
NProgress.done()
}
return Promise.reject(err)
})
// // 请求方法
// return new Promise((resolve, reject) => {
// axios({
// url: url,
// method: method,
// data: data || {},
// })
// .then((res) => {
// resolve(res.data)
// })
// .catch(err => {
// reject(err)
// })
// })
}
添加 react router
// 路由配置使用常规路由
import * as React from 'react'
import { Switch, Route, Router } from 'react-router-dom'
import Home from '../pages/home/Home'
import About from '../pages/about/About'
import { history } from '../utils/history'
const MyRouter = () => {
return (
<Router history={history}>
<Switch>
<Route path='/' exact component={Home} />
<Route path='/about' component={About} />
</Switch>
</Router>
)
}
export default MyRouter
添加 reudx
actions
// actions/index.ts
// 省略非关键性代码 actions
reducres
// reducres/index.ts
import { combineReducers } from 'redux'
const root = combineReducers({
})
export default root
store
// store/index.ts
import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import reducres from '../reducers'
const middlewares = [thunk, logger]
const store = createStore(reducres, applyMiddleware(...middlewares))
export { store }
在页面使用
// index.ts
// 省略非关键性代码
// ...
<Provider store={store}>
<MyRouter/>
</Provider>
添加配置