zoukankan      html  css  js  c++  java
  • [React] Optimistic UI update in React using setState()

    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}`,
          }))
        );
      };
    
      // ...
    }
  • 相关阅读:
    mybatis之关联关系映射
    spa项目开发之tab页实现
    mybatis整合redis实现二级缓存
    mybatis整合spring
    mybatis动态sql和分页
    Mybatis入门
    使用java代码操作redis
    Redis安装
    IDEA的安装和使用
    Linux入门——安装jdk、tomcat、MySQL以及项目部署
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8330307.html
Copyright © 2011-2022 走看看