码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Optimistic UI update in React using setState()

时间:2018-01-22 19:15:25      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:hot   target   post   failure   eve   where   loading   power   href   

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

  // ...
}

 

[React] Optimistic UI update in React using setState()

标签:hot   target   post   failure   eve   where   loading   power   href   

原文地址:https://www.cnblogs.com/Answer1215/p/8330307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!