博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Optimistic UI update in React using setState()
阅读量:4964 次
发布时间:2019-06-12

本文共 1307 字,大约阅读时间需要 4 分钟。

In this lesson we will refactor an existing UI update from a typical loading approach to an optimistic UI updateapproach to give our users a faster, more snappy experience. Instead of displaying a "loading" UI to our users while our request is in progress, we will immediately update the UI and account for reverting state and displaying an error in the event of a failure. We can accomplish this relatively easily in React, thanks to the simplicity and power of  combined with making use of Javascript's .

 

class App extends React.Component {  // ...  deleteItemOptimistic = id => {    // 1) Snapshot target item so we can restore it in the case of failure    const deletingItem = this.state.items.find(item => item.id === id);    // 2) Assume success. Immediately update state    this.setState(state => ({      items: state.items.filter(item => item.id !== id),    }));    // 3) If the request failed revert state and display error.    deleteItemRequest(id).catch(() =>      this.setState(state => ({        // Restore the single, deleted item.        // Use sort to ensure it is inserted where expected.        items: [...state.items, deletingItem].sort((a, b) => a.id - b.id),        error: `Request failed for item ${id}`,      }))    );  };  // ...}

 

转载于:https://www.cnblogs.com/Answer1215/p/8330307.html

你可能感兴趣的文章
shell中的数值运算
查看>>
23种设计模式之六(工厂模式)
查看>>
HashSet、TreeSet和LinkedHashSet分别基于HashMap、TreeMap和LinkedHashMap
查看>>
maven 添加json-lib包 or自定义jar包
查看>>
linux之ssh服务
查看>>
Xcode工程各个文件夹作用及新建工程参数含意
查看>>
while用法
查看>>
码流识别与传输
查看>>
关于H5页面在微信浏览器中视频播放的问题
查看>>
01.Python基础-1.Python简介及基础
查看>>
自定义注解
查看>>
poj 2299 归并排序求逆序数 (可做模板)
查看>>
图论浅析--最小生成树之Prim
查看>>
ora-01031:insufficient privileges解决方法 - 转
查看>>
log4j详解(二)
查看>>
滚动条
查看>>
数据结构之---C语言实现图的邻接表存储表示
查看>>
自动提交Git branch代码评审到Review Board系统
查看>>
javaoop_pst和rst和cst
查看>>
【转载】自定义地图数据瓦片化请求的一种实现方案
查看>>