gpt4 book ai didi

reactjs - 使用 Flux 进行乐观更新(异步)

转载 作者:行者123 更新时间:2023-12-03 14:15:24 26 4
gpt4 key购买 nike

我正在尝试向我的 Flux 模型添加乐观更新。我将 UI 操作调度和服务器操作调度合并为一个操作。我在 Action 创建器中的代码如下所示:

deleteItem: function(itemId) {

// optimistic update
WebshipDispatcher.handleServerAction({
type: ActionTypes.DELETE_ITEM,
deleteStatus: 'success',
itemId: itemId
});

// now let's actually check if that was the correct result
AppAjaxUtil.get('/deleteItem', {itemId: itemId}, function(result) {

WebshipDispatcher.handleServerAction({
type: ActionTypes.DELETE_ITEM,
deleteStatus: result.status, // 'success' or 'failure'
itemId: itemId
});

}, function(error) {

WebshipDispatcher.handleServerAction({
type: ActionTypes.DELETE_ITEM,
error: error
});

});
}

这是允许乐观更新的适当方式还是我错误地思考了这篇文章?

最佳答案

@fisherwebdev 是对的。真正的逻辑将发生在您的商店中。例如,当某个项目删除失败时,您将如何处理逻辑?它自己就变成了野兽。除非您得到服务器的确认,否则您确实不想从商店中删除该商品。像 Ext 这样的库在等待服务器的成功响应时将记录标记为脏记录。因此更新仍然乐观地发生,但如果服务器出现故障,用户和记录会收到通知。

因此,您的商店中可能有一组记录,当您的服务器成功响应时,这些记录将被删除。这很粗糙,但类似于以下内容:

deleteItem: function(itemId) {

// optimistic update
WebshipDispatcher.handleServerAction({
type: ActionTypes.MARK_ITEM_AS_DIRTY,
deleteStatus: 'success',
itemId: itemId
});

// now let's actually check if that was the correct result
AppAjaxUtil.get('/deleteItem', {itemId: itemId}, function(result) {

WebshipDispatcher.handleServerAction({
type: result.status ? ActionTypes.DELETE_ITEM : ActionTypes.DELETE_ITEM_FAIL,
deleteStatus: result.status, // 'success' or 'failure'
itemId: itemId
});

}, function(error) {

WebshipDispatcher.handleServerAction({
type: ActionTypes.DELETE_ITEM_FAIL,
error: error,
itemId: itemId
});

});
}

所以基本上,如果您的响应成功,您就会从商店中删除脏记录。否则,您的商店中会有脏记录的引用,可以在您的应用程序仍在运行时在幕后使用服务器重试。因此,本质上您的用户不必坐下来等待响应。

关于reactjs - 使用 Flux 进行乐观更新(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27993155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com