我应该将承诺存储在Redux中吗? [英] Should I store promises in Redux?

查看:111
本文介绍了我应该将承诺存储在Redux中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在在线食品订购应用程序中使用Redux和React.

I'm using Redux and React in an online food-ordering app.

当用户从购物篮中取出物品时,我需要向服务器发出XHR请求,以计算购物篮的新总价. XHR完成后,我将更新redux存储并渲染新价格.我正在使用Redux thunk来管理此异步操作.

When the user removes an item from their basket, I need to fire off an XHR request to the server to compute the new total price for the basket. When this XHR completes, I update the redux store and render the new price. I'm using Redux thunk to manage this async operation.

有一个问题,就是用户迅速从篮子中取出了两个物品.用户删除了第一个项目,然后我解雇了XHR以获取新价格.然后,用户单击按钮以删除第二个项目,并触发第二个XHR.

There is a problem is a user removes two items from the basket in quick succession. The user removes the first item, and I fire off an XHR to get the new price. Then the user clicks a button to remove a second item, and a second XHR is fired off.

如果第二个XHR在第一个XHR之前完成,则UI将处于不正确的状态-将显示仅删除第一个项目的购物篮的价格.

The UI will be in an incorrect state if the second XHR completes before the first - the price of the basket with only the first item removed will be shown.

要解决此问题,我想在用户单击按钮以删除第二个项目时取消第一个(进行中的)XHR.要取消第一个XHR,我需要跟踪Promise对象(我正在使用 axios 来管理XHR ).

To work around this, I want to cancel the first (in-flight) XHR when the user clicks the button to remove the second item. To cancel the first XHR I need to keep track of the promise object (I'm using axios to manage XHR).

将飞行中的XHR存储在redux存储区中对我来说很有意义.这样将承诺存储在Redux中是不好的做法吗?似乎不赞成-Redux实际上应该只存储纯数据.

It makes sense to me to store the in-flight XHR in the redux store. Is it bad practice to store promises in Redux like this? It seems to be frowned upon - Redux should really just be storing plain data.

推荐答案

Redux FAQ中的

This is covered in the Redux FAQ, at http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-non-serializable :

强烈建议您仅将简单的可序列化对象,数组和基元放入存储中.从技术上讲,可以将不可序列化的项目插入商店中,但是这样做会破坏保留和重新存储商店内容的能力,并干扰时间旅行调试.

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store, as well as interfere with time-travel debugging.

通常,任何这样的异步行为都通过Redux-thunk,redux-saga或redux-observable等promise或中间件在Redux存储中进行外部处理.有关这些方法之间的一些比较,请参见最近的文章 Redux 4种方法 3种常见的Redux副作用方法.

Generally, any async behavior like this is handled externally to the Redux store, via promises or middleware like redux-thunk, redux-saga, or redux-observable. For some comparisons between these approaches, see the recent articles Redux 4 Ways and 3 Common Approaches to Side-Effects in Redux.

这篇关于我应该将承诺存储在Redux中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆