學習路上禿廢猛進

or_so發表於2018-12-03

基於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();
  },
};
複製程式碼

相關文章