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

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

问题描述

我在一个在线食品订购应用中使用 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 在第一个之前完成,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,我需要跟踪承诺对象(我使用 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 中存储 promise 是不好的做法吗?这似乎令人不悦——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 常见问题解答中有所介绍,位于 http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-non-serializable:

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 存储外部处理的,通过 promise 或中间件(如 redux-thunk、redux-saga 或 redux-observable).有关这些方法之间的一些比较,请参阅最近的文章 Redux 4 Ways3 种应对 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 中存储 promise 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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