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 setState() combined with making use of Javascript's lexical scoping and closures.

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}`,
}))
);
}; // ...
}

最新文章

  1. Contiki-一个进程的例子
  2. 用H5的canvas做时钟
  3. 白话学习MVC(五)Controller的激活
  4. Python缩进
  5. VS2012网布网站与IIS配置
  6. 服务器安装Linux应该注意的问题
  7. Cocos2d-x单机游戏防八门神器修改数据
  8. Python subprocess Popen
  9. 如何学习Javascript ?
  10. opencv中的vs框架中的Blob Tracking Tests的中文注释。
  11. Xcode8.2 继续使用插件
  12. java面向对象(一)
  13. 移动商城第四篇【Controller配置、添加品牌之文件上传和数据校验】
  14. [Elasticsearch] 邻近匹配 (二) - 多值字段,邻近程度与相关度
  15. Unity AssetBundle的几个加载方式
  16. IPerf——网络测试工具介绍与源码解析(3)
  17. java多线程面试题小结
  18. Vue proxyTable 解决开发环境的跨域问题
  19. Java学习笔记42(序列化流)
  20. linux中日历命令显示

热门文章

  1. AT1145 ホリドッグ
  2. Linux下MySql数据库常用操作
  3. 兴趣爱好-QQ的本地共享
  4. spring boot pom
  5. Linux操作系统是如何工作的
  6. DGA ngram kmeans+TSNE用于绘图
  7. spring 发送邮件代码示例(带附件和不带附件的)
  8. Visual Studio 2015 官方下载及密钥
  9. (转载) Android开发时,那些相见恨晚的工具或网站!
  10. 使用Mapping实现的以太坊智能合约的代码