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}`,
          }))
        );
      };
    
      // ...
    }
  • 相关阅读:
    hdu5926Mr. Frog’s Game
    hdu5926Mr. Frog’s Game
    hdu5924Mr. Frog’s Problem
    hdu5924Mr. Frog’s Problem
    hdu5922Minimum’s Revenge
    hdu5922Minimum’s Revenge
    带空格的字符串输入
    带空格的字符串输入
    382. Linked List Random Node
    319. Bulb Switcher
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8330307.html
Copyright © 2011-2022 走看看