简体   繁体   English

我应该在Redux中存储承诺吗?

[英]Should I store promises in Redux?

I'm using Redux and React in an online food-ordering app. 我在一个在线食品订购应用程序中使用Redux和React。

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. 当用户从购物篮中移除商品时,我需要向服务器发出XHR请求以计算购物篮的新总价。 When this XHR completes, I update the redux store and render the new price. 当XHR完成时,我更新redux商店并呈现新价格。 I'm using Redux thunk to manage this async operation. 我正在使用Redux thunk来管理这个异步操作。

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. 用户删除第一个项目,然后我关闭XHR以获得新价格。 Then the user clicks a button to remove a second item, and a second XHR is fired off. 然后,用户单击按钮以删除第二个项目,并触发第二个XHR。

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之前完成,则UI将处于不正确的状态 - 将仅显示仅删除了第一个项目的篮子的价格。

To work around this, I want to cancel the first (in-flight) XHR when the user clicks the button to remove the second item. 要解决此问题,我想在用户单击按钮删除第二个项目时取消第一个(飞行中)XHR。 To cancel the first XHR I need to keep track of the promise object (I'm using axios to manage XHR). 要取消第一个XHR,我需要跟踪promise对象(我正在使用axios来管理XHR)。

It makes sense to me to store the in-flight XHR in the redux store. 我将飞行中的XHR存储在redux商店中是有意义的。 Is it bad practice to store promises in Redux like this? 在Redux中存储承诺是不是很糟糕吗? It seems to be frowned upon - Redux should really just be storing plain data. 这似乎令人不悦--Redux应该只是存储普通数据。

This is covered in the Redux FAQ, at http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-non-serializable : 这可以在Redux FAQ中找到,网址是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. 从技术上讲,可以将不可序列化的项目插入到商店中,但这样做会破坏保存和补充商店内容的能力,并且会干扰时间旅行调试。

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. 通常,任何像这样的异步行为都是通过promises或中间件(如redux-thunk,redux-saga或redux-observable)在Redux存储外部处理的。 For some comparisons between these approaches, see the recent articles Redux 4 Ways and 3 Common Approaches to Side-Effects in Redux . 有关这些方法之间的一些比较,请参阅最近的文章Redux 4方法Redux 中副作用的3种常用方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM