首页 > 其他 > 详细

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

时间:2018-01-22 18:57:29      阅读:257      评论:0      收藏:0      [点我收藏+]

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()

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!