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 为例只是项目开发的一个缩影,这种封装思想是可以在工作中借鉴的。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。