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