react.js fetch 基于单例+轻提示(toast)的简单封装
Services
/* eslint-disable no-useless-constructor */import config from './config.js';import 'whatwg-fetch'
import toast from '../toast/index.js'export default class Services {constructor() { }// 单例static getInstance() {if (!Services.instance) {Services.instance = new Services();return Services.instance;}return Services.instance;}post(action, data) {toast.loading("加载中")return fetch(config.base_url + action, {method: 'POST', // or 'PUT'body: JSON.stringify(data),headers: {'Accept': 'application/json','Content-Type': 'application/json'}}).then(res => res.json())}get(action) {toast.loading("加载中")return fetch(config.base_url + action).then(response => {return response.json()})}get1(action) {return fetch(action).then(response => {return response.json()})}
}
config.js
export default {base_url: '请求地址'
}
轻提示
import React from 'react'
import ReactDOM from 'react-dom'
import Toast from './toast'
import './toast.css'function createNotification() {const div = document.createElement('div')document.body.appendChild(div)const notification = ReactDOM.render( < Toast / > , div)return {addNotice(notice) {return notification.addNotice(notice)},destroy() {ReactDOM.unmountComponentAtNode(div)document.body.removeChild(div)}}
}
let notification
const notice = (type, content, duration = 2000, onClose) => {if (!notification) notification = createNotification()return notification.addNotice({ type, content, duration, onClose })
}export default {info(content, duration, onClose) {return notice('info', content, duration, onClose)},success(content = '操作成功', duration, onClose) {return notice('success', content, duration, onClose)},error(content, duration, onClose) {return notice('error', content, duration, onClose)},loading(content = '加载中...', duration = 0, onClose) {return notice('loading', content, duration, onClose)}
}
import React, { Component } from 'react'class ToastBox extends Component {constructor() {super()this.transitionTime = 300this.state = { notices: [] }this.removeNotice = this.removeNotice.bind(this)}getNoticeKey() {const { notices } = this.statereturn `notice-${new Date().getTime()}-${notices.length}`}addNotice(notice) {const { notices } = this.statenotice.key = this.getNoticeKey()// notices.push(notice);//展示所有的提示notices[0] = notice;//仅展示最后一个提示this.setState({ notices })if (notice.duration > 0) {setTimeout(() => {this.removeNotice(notice.key)}, notice.duration)}return () => { this.removeNotice(notice.key) }}removeNotice(key) {const { notices } = this.statethis.setState({notices: notices.filter((notice) => {if (notice.key === key) {if (notice.onClose) setTimeout(notice.onClose, this.transitionTime)return false}return true})})}render() {const { notices } = this.stateconst icons = {info: 'toast_info',success: 'toast_success',error: 'toast_error',loading: 'toast_loading'}return (<div className="toast">{notices.map(notice => (<div className="toast_bg" key={notice.key}><div className='toast_box'><div className={`toast_icon ${icons[notice.type]}`}></div><div className='toast_text'>{notice.content}</div></div></div>))}</div>)}
}export default ToastBox
.toast {position: fixed;left: 0;top: 0;z-index: 999;display: flex;flex-direction: column;
}.toast_bg {position: fixed;width: 100%;height: 100%;left: 0;top: 0;
}.toast_box {/*背景框*/position: relative;left: 32%;top: 20%;width: 6rem;height: 1rem;margin: -1rem -1.4rem;background: rgba(0, 0, 0, 0.65);border-radius: .1rem;color: #fff;
}.toast_text {/*文字*/position: absolute;bottom: 30%;text-align: center;width: 90%;margin: 0 5%;height: 0.5rem;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;
}.toast_icon {/*图标*/position: relative;left: 10%;top: 15%;margin: -.4rem;width: .8rem;height: .8rem;
}/*content 提示内容 string(loading方法为可选)
duration 提示持续时间 number,单位ms(可选)
onClose 提示关闭时的回调函数(可选)
Toast.error('加载完成',1000,()=>{})
*/.toast_loading {/*Toast.loading('加载完成')*/-webkit-animation: loading 1s steps(12, end) infinite;animation: loading 1s steps(12, end) infinite;background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAM1BMVEUAAAD///+3leKCAAAAEHRSTlMAENCA8KAgsGDgQMCQUDBwhylaLQAAAL1JREFUOMu9U0kSwyAMK9jsS/T/1zZt2pgEZzq9RBeMZYRGDI/70bO5JptjrOAQVTonIJVK5bW2ma9A7VvpK8OdeQfbZectrDnyU+Oo0b68wGK0muDPdxpOciaizq5pkAgiIPAoew2rBVNYZoM2YHbZDNKz/2Ogam3ff5gMEL8wisfh2KKZiFiGWFkk1B7NSbhNQFy4M2+PghbODNsg7y8THM2njiy8gBgcaEUA9GgNJbxh6fJv+NxiFvYmPAFtCQZNK1qZIAAAAABJRU5ErkJggg==") no-repeat;background-size: 100%;
}.toast_success {/*Toast.success('加载完成')*/background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAM1BMVEUAAAD///+3leKCAAAAEHRSTlMA8DAQ0GBP4LCggMBwIJBAIttdjAAAAINJREFUOMvdkUsOwyAMBbH5hUCauf9pK1SlohF438x2LPn52f09+8vUfiNb/gighj8FouEjYCUoQDXiBSD7pdcMiK7XC9wCFmlDO3T20Scgx287ne13pwDU89NOJ3g3maCmJDANqIGRtLj8oi1ed1GMdmcB7wXIYX8QdQZJiM5Em3smbyVICDCOrCqSAAAAAElFTkSuQmCC") no-repeat;background-size: 100%;
}.toast_error {/*Toast.error('加载完成')*/background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAMFBMVEUAAAD///87TQQwAAAAD3RSTlMA0BDAMODwUKBgsCCAQJClzVPvAAAA0UlEQVQoz2MgErAclv9o44Dgc8b/B4KvBTA+t/3XdgeWivjPG6ACbl8ngNXlp0AN+L8IwtD6DzFm2w+Y3v5sMGW/ACbA9Rms9ZsCTIApH2QR608GhoUKQJ4xA8P8AKCAP5CwF2JgUPwIlPwCFDj/AMRRYJIHCnL8AZkJ1AfkAcUYGNhBpso7MICUgBQw8H4EEv/B5ssDFYA4mAKYWjANfd+Aai3CYZ9BDoM63RDkdEGQ0zE9h+l9zADCDEIGt2/wQEZEwwVepGhgYEdEFGZUEgYAW05XI3jSsVwAAAAASUVORK5CYII=") no-repeat;background-size: 100%;
}.toast_info {/*Toast.info('普通提示')*/background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAALVBMVEUAAAD///+hSKubAAAADnRSTlMA4CCAwKBAMJBg8NAQUNhWlbcAAAC+SURBVCjPYyASsLfse+1cgOBzyr0DgocXYHwmv4dtCkwZck8UoAJZDydA1C2H8NnexUAYR99BjNF6CtMbtwhM+QUACUUhIMH6BKz14QEgafcYSPDIgSxifMkAE2CYJwAk6gQQAozPgURfA0KAA0T6JSAE2ECm7lNACDC9BhLvGGACIA6GAFyLohBEC9xQqLeeQKwFA4i1EIfBAeNzuNMVhSBOx/AcpvcxAwgzCDEDGTMaGHhhEYWIShN4VBIGAPvRT5YzufhUAAAAAElFTkSuQmCC") no-repeat;background-size: 100%;
}@-webkit-keyframes loading {0% {-webkit-transform: rotate3d(0, 0, 1, 0deg);transform: rotate3d(0, 0, 1, 0deg);}100% {-webkit-transform: rotate3d(0, 0, 1, 360deg);transform: rotate3d(0, 0, 1, 360deg);}
}@keyframes loading {0% {-webkit-transform: rotate3d(0, 0, 1, 0deg);transform: rotate3d(0, 0, 1, 0deg);}100% {-webkit-transform: rotate3d(0, 0, 1, 360deg);transform: rotate3d(0, 0, 1, 360deg);}
}
调用
//post方式myservices.getInstance().post("masterlogin",{"account":values.name,"password":values.password}).catch(error => {console.error('Error:', error)toast.error("请求失败")}).then(response => {console.log('Success:', response)// eslint-disable-next-line eqeqeqif(response==undefined){toast.info("登录失败!")}else{toast.success("登录成功!")sessionStorage.setItem("master",JSON.stringify(response.master));this.props.history.push('/home_page');}//get方式// myservices.getInstance().get(`login?account=${values.name}&password=${values.password}`)//.catch(error => console.error('Error:', error))// .then(response => console.log('Success:', response));
————————————————
原文链接:https://blog.csdn.net/lmsfv/article/details/105155547
react.js fetch 基于单例+轻提示(toast)的简单封装相关推荐
- nodejs操作sqlserver数据_nodejs基于mssql模块连接sqlserver数据库的简单封装操作示例...
本文实例讲述了nodejs基于mssql模块连接sqlserver数据库的简单封装操作.分享给大家供大家参考,具体如下: 注意:开启sqlserver服务器允许远程连接的步骤,自行百度,很多经验,no ...
- nodejs操作sqlserver数据_实例分析nodejs基于mssql模块连接sqlserver数据库的简单封装操作...
本文主要介绍了nodejs基于mssql模块连接sqlserver数据库的简单封装操作,结合实例形式分析了nodejs中mssql模块的安装与操作sqlserver数据库相关使用技巧,需要的朋友可以参 ...
- js与设计模式----单例
通常我们会有这样的需求,制作一个模态窗口,我们用一个与body一样大的div来覆盖整个页面,当作一个荫罩层,那么此div应该是全局的而且唯一的. 利用js闭包的特性,写出以下代码. var creat ...
- Java设计模式-单例设计模式
文章目录 前言 一.什么是设计模式? 二.单例模式介绍 1.单例模式的目的 2.单例模式的定义 单例模式的设计与实现要点: 3.单例模式的两种实现方式 (一)饿汉式创建 (二)懒汉式创建 4.单例模式 ...
- iOS之深入解析单例的实现和销毁的底层原理
一.单例的概念 单例设计模式确保对于一个给定的类只有一个实例存在,这个实例有一个全局唯一的访问点.它通常采用懒加载的方式在第一次用到实例的时候再去创建它. 单例可以保证在程序运行过程,一个类只有一个实 ...
- Fort.js – 时尚、现代的进度提示效果
Fort.js 是表单填写进度提示效果的 JavaScript 库,使用非常简单. 提供了Default.Gradient.Sections 以及 Flash 四种效果 用Fort.js很简单,很简单 ...
- 【深入设计模式】单例模式—从源码分析内部类单例、枚举单例以及单例模式在框架中的应用
文章目录 1. 使用静态内部类实现单例模式 1.1 静态内部类单例写法 1.2 如何实现懒加载 1.3 为什么线程安全 2. 枚举类型单例单例模式 2.1 枚举类型单例写法 2.2 枚举类型单例原理 ...
- filter java 是单例的吗_JAVA 设计模式之 单例模式详解
单例模式:(Singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点.单例模式是创建型模式.单例模式在现实生活中应用也非常广泛. 在 J2EE 标准中,S ...
- Spring 框架中的单例Beans 是线程安全的么?
Spring 框架并没有对单例bean 进行任何多线程的封装处理.关于单例bean 的线程安全和并发问题需要开发者自行去搞定.但实际上,大部分的Spring bean 并没有可变的状态(比如Servi ...
最新文章
- C语言经典例100-将学生成绩写入文件
- (59)简单介绍RAM IP核类型和接口信号?
- 双电容单相电机接线图解_单相电机要用电容,三相电机为何不需要?
- 如何分组Windows窗体单选按钮?
- 如何从JavaScript中的对象数组中获得不同的值?
- JQuery中关于html()、text()、val()三者之间的区别
- DNN群宗旨--QQ群(DNN山海经):56782274
- Effective C++ 之 Item 5:了解C++默默编写并调用哪些函数
- w10用计算机卸载,win10电脑卸载系统内置应用软件的简单方法
- 用Python给喜欢的女孩写一个办公小工具,她说棒极了
- Excel表Ctrl+v和Ctrl shift+v有什么区别_Excel表格操作技巧,超实用
- Pytorch:Unet网络代码详解
- 基于matlab的眼部疲劳检测
- RTP/RTCP工程实践与问题解决方案(合集)
- linux inactive,linux – systemctl status显示inactive dead
- 如何用Navicat连接mongoDB
- Not Shading
- 如何将多个bin文件合成一个bin文件?(二)
- Excel单变量求解实例操作演示
- 创新工场2011年校园招聘笔试题
热门文章
- 【论文阅读】CAFE: Catastrophic Data Leakage in Vertical Federated Learning
- 南大通用GBase XDM 支持的核心技术规范
- 反射大师怎么使用_转转大师OCR怎么使用 转转大师OCR使用教程
- Java程序设计教程与实训_Java程序设计教程与项目实训
- 真我GT realme GT root权限 解锁BL 刷ROOT教程 免费 TWRP
- 一段动词和五段动词 说明
- 计算机应用基础IE浏览器设置,计算机应用基础IE浏览器设置学习笔记
- 如何组建优秀的APP开发团队
- 使用百度echarts仿雪球分时图(一)
- baiduMap试手《办理进京证和市区警察查询进京证的地址浏览》