学习路上秃废猛进

209 阅读1分钟

基于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();
  },
};