Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react工程中使用typescript(二), 添加请求 axios 、路由、redux #24

Open
gaowei1012 opened this issue Aug 31, 2020 · 3 comments

Comments

@gaowei1012
Copy link
Owner

添加配置

@gaowei1012 gaowei1012 changed the title 在react工程中使用typescript(二), 添加请求 axios 、路由、redux react工程中使用typescript(二), 添加请求 axios 、路由、redux Aug 31, 2020
@gaowei1012
Copy link
Owner Author

添加 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)
    //     })
    // })
}

@gaowei1012
Copy link
Owner Author

添加 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

@gaowei1012
Copy link
Owner Author

gaowei1012 commented Aug 31, 2020

添加 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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant