# 1、结构:

├── services
    ├── index.js
    ├── request # axios封装
    │   ├── index.js
    │   └── config.js
    └── modules # api管理
        ├── cart.js
        └── products.js
// @/services/index.js

import RenRequest from './request/index.js'
import { BASE_URL, TIMEOUT } from './request/config.js'

export const shopRequest = new RenRequest({
  baseURL: BASE_URL,
  timeout: TIMEOUT
})

export * from './modules/cart.js'

# 2、axios 封装:

// @/services/request/config.js

export const BASE_URL = 'http://xxxxx.com'
export const TIMEOUT = 10000
// @/services/request/index.js

import axios from 'axios'

class RenRequest {
  constructor(config) {
    this.instance = axios.create(config)

    // 响应拦截
    this.instance.interceptors.response.use(
      (response) => {
        return response.data
      },
      (error) => {
        return error
      }
    )
  }

  request(config) {
    return this.instance.request(config)
  }

  get(config) {
    return this.request({ ...config, method: 'get' })
  }

  post(config) {
    return this.request({ ...config, method: 'post' })
  }
}

export default RenRequest

# 3、api 管理:

// @/services/modules/cart.js

import { shopRequest } from '../index.js'

export function getCartList(offset = 0, size = 20) {
  return shopRequest.get({
    url: 'carts/list',
    params: {
      offset,
      size
    }
  })
}

# 4、使用示例:

  • React-Redux 中
react-redux 模块化的目录结构
├── store
    ├── index.js
    ├── cart
    │   ├── index.js
    │   ├── constants.js
    │   ├── reducer.js
    │   └── actionCreators.js
    └── products
        ├── index.js
        ├── constants.js
        ├── reducer.js
        └── actionCreators.js
// @/store/cart/actionCreators.js
import { getCartList } from '@/services/modules/cart'

export const changeCartListAction = (payload) => ({
  type: CHANGE_CART_LIST,
  cartList: payload
})

export const fetchCartListAction = ({ offset, size }) => {
  return async (dispatch, getState) => {
    const res = await getCartList(offset, size)

    // 将获取的数据存储到 redux 中
    dispatch(changeCartListAction(res.data))
  }
}
  • Redux Toolkit 中

  • 组件应用中
import { fetchCartListAction } from '@/store/cart/actionCreators'

const Cart = memo(() => {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchRoomListAction())
  }, [dispatch])
})
更新于 : 8/7/2024, 2:16:31 PM