banner
他山之石

他山之石

React Native 封裝HTTP請求

作為一個前端開發者,我覺得 React Native 也是一個很酷的東西,本文不涉及 React Native 的開發相關,只是總結了開發中的一些最佳實踐。不僅僅適合 React Native。

image

在進行專案開發時,我們都會將公共的模塊抽離出來。在學習 React Native 的過程中,我也遇到了同樣的場景,在此記錄下來。React Native 使用 fetch 作為網絡請求庫,而每個幾乎每個模塊都需要用到網絡請求,那麼將其抽離為公共模塊甚為必要。

封裝 HTTP 模塊的優點#

  • 代碼複用

由於很多模塊都會用到 HTTP 請求,將 fetch 封裝為公共模塊可以複用很多代碼

  • 高內聚低耦合

將公共部分提取出來,可以使每個模塊專注於自身的業務邏輯

  • 便於專案的擴展與後期的維護,並且做到職責分離

具體做法#

首先,在專案根目錄下新建 utils 目錄,在 utils 目錄中,新建 fetch.js。

要想在其他模塊中使用整個模塊,首先,我們要將其導出為一個模塊供其他模塊使用。

export default class fetchUtils {
    
}

fetchUtils 模塊中應該包含兩個方法,分別是 get 和 post 的請求方法,下一步,來編寫 get 方法。

static get(url) {
    return new Promise((resolve, reject) => {
      fetch(url)
          .then(response => response.json())
          .then((result) => {
              resolve(result);
          })
          .catch(error => {
              reject(error);
          })

    })
}

get 方法應該是一個靜態方法,接受一個參數 url,其返回一個 Promise,Promise 接受兩個參數 resolve 和 reject,用於處理成功和失敗的情況,在 Promise 中,使用 fetch 發起 get 請求,然後使用鏈式函數 then 來處理伺服器返回結果,先取出 json 數據,當伺服器成功返回數據,使用 resolve 返回結果;當發生錯誤時,調用 catch 方法捕獲錯誤。

下面是 post 方法。

static post(url, data) {
    return new Promise((resolve, reject) => {
        fech(url, {
            method: 'POST',
            header: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then((result) => {
            resolve(result);
        })
        .catch(error => {
            reject(error);
        })
    })
}

post 方法與 get 方法類似,也是靜態方法,post 方法接受兩個參數,分別是 url 和提交的數據 data。同樣的,post 方法返回一個 Promise,參數與 get 方法一樣,然後向伺服器發送 POST 請求,post 請求需要設置 method 為 POST,還需要設置請求頭,請求頭包含接受的數據類型和 Content-Type,均設置為 application/json,最後將用戶提交的數據放到 body 中,使用 JSON 序列化 data。然後需要接受伺服器返回的數據,這裡與 get 方法一樣,不再贅述。

以上就是封裝好的 HTTP 請求模塊。下面看一下如何使用。

首先,將 fetchUtils 導入。

import fetchUtils from '../utils/fetch'

get 方法

fetchUtils.get(url)
    .then(result => {
        this.setState({result: JSON.stringify(result)})
    })
    .catch(error => {
         this.setState({result: JSON.stringify(error)})
    })

post 方法

fetchUtils.post(url, data)
    .then(result => {
        this.setState({result: JSON.stringify(result)})
    })
    .catch(error => {
         this.setState({result: JSON.stringify(error)})
    })

總結#

通過以上對 fetch 方法的封裝,使代碼更加精簡,業務邏輯更加清晰,也更加容易維護。此處使用 React Native 為例只是專案開發的一個縮影,這種封裝思想是可以在工作中借鑒的。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。