0

我正在使用 Reactjs 和 Redux 开发一个应用程序。我有一个要求,我需要从列表中删除该项目。此处删除功能一切正常,但我需要为用户提供撤消删除的选项。我目前的方法是

return dispatch => {
        dispatch(deletePosts(postID));

        return fetch(API.url(postID), {
            method: API.type,
            credentials: 'same-origin'
        }).then(function(response) {
           if(!response.ok) {
            //revert back
           }
        });
    }

这里我先从状态中删除帖子,然后调用 fetch 请求从服务器中删除。但是如果我给任何这样的功能来逆转,我不能只是从服务器中删除。我认为显示撤消选项大约 3 秒并执行操作是合理的。您能否帮助我如何实现这一点,以及是否有任何其他 Web 应用程序实现了这一点。谢谢

4

2 回答 2

2

You have two options. First, to implement this logic on the client side:

  1. When user clicks "delete" button you should mark post in your state as toBeDeleted but don't send real delete request to the server.

  2. Delay calling of your deletePostForReal action using setTimeout for 3 seconds.

  3. Your list component should show "cancel" button instead of post if it is marked as toBeDeleted.

  4. If user user clicks "Cancel" – remove toBeDeleted field from the post.

  5. In your delayed deletePostForReal action check if post has toBeDeleted field. If yes, send real request to the server and remove post from the store. If no – don't do anything.

Second option is to do it on the server side. In that case your server should implement similar logic itself and provide different endpoints for the client side. For example post/ID/delete and post/ID/undo_delete.

于 2016-03-02T14:32:03.610 回答
2

保留对列表初始状态的引用,然后创建一个删除项目的副本,然后在必要时恢复到初始状态。

const postsBefore = getPosts();

deletePosts(postID);

return fetch(API.url(postID), {
  method: API.type,
  credentials: 'same-origin'
}).then(function(response) {
  if(!response.ok) {
    revertPosts(postsBefore);
  }
});

重要的是您的减速器不要执行突变,否则您的删除功能会修改原始数据结构,这也会改变您的postsBefore参考。当您尝试恢复到 时postsBefore,您将恢复到完全相同的数据。

于 2016-02-29T07:36:06.120 回答