学习路上秃废猛进

本文介绍了一种基于fetch API的请求封装方法,包括错误处理和数据解析,同时展示了如何在React中使用自定义的判断组件及debounce函数优化用户体验。

基于fetch的封装

import fetch from 'fetch';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}
也可以和async 、 await 一起使用

getData = async () => {
    const { success, error, data } = await request('url');
    ||
    const { success, error, data } = await request('url', {
        method: 'POST || PUT || DELETE',
        headers: {
            "Content-type":"application:/x-www-form-urlencoded:charset=UTF-8",
        },
        body: JSON.stringify(body)
    });
    // 进行数据的操作
    ...
}
复制代码

优化判断的If 组件

for example:
{
    aaa
    && aaa.indexOf('xxx')
    && <div>{aaa}</div>
}
但是对于多层条件判断并不友好象,下面编写一个判断组件进行优化
import { PureComponent } from 'react';

export default class If extends PureComponent {
  render() {
    const { children, condition } = this.props;
    return condition ? children : null;
  }
}
用法
<If condition={aaa && aaa.indexOf('xxx') > 0}>
    <div>{aaa}</div>
</If>

复制代码

封装debounce函数

let timer = false;
export const debounce = (cb = () => { }, time = 450) => {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        cb();
    }, time);
};
可用于搜索组件
debounce(() => {})

复制代码

封装localStorage

const storage = window.localStorage;

const LocalStorage = {
  add: (key, value) => {
    if (typeof value === 'object') {
      value = JSON.stringify(value);
    }
    storage.setItem(key, value);
  },
  // 覆盖原先的对象
  addCoverObject: (key, value) => {
    if (typeof value === 'string') {
      value = JSON.parse(value);
    }
    let storageValue = storage.getItem(key);
    let resValue = {};
    if (storageValue) {
      storageValue = JSON.parse(storageValue);
      resValue = { ...storageValue, ...value };
    } else {
      resValue = value;
    }
    LocalStorage.add(key, resValue);
  },
  get: (key) => {
    return storage.getItem(key);
  },
  remove: (key) => {
    storage.removeItem(key);
  },
  clear: () => {
    storage.clear();
  },
};
复制代码

转载于:https://juejin.im/post/5c049df2e51d4522087082a7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值