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

Should I store promises in Redux?

我在在线订餐应用程序中使用 Redux 和 React。

当用户从他们的购物篮中移除商品时,我需要向服务器发出 XHR 请求以计算购物篮的新总价。当这个 XHR 完成时,我更新 redux store 并呈现新价格。我正在使用 Redux thunk 来管理这个异步操作。

用户快速连续从购物篮中取出两件商品时出现问题。用户删除第一个项目,然后我启动 XHR 以获得新价格。然后用户单击按钮删除第二个项目,第二个 XHR 被触发。

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

为了解决这个问题,我想在用户单击按钮删除第二个项目时取消第一个(运行中的)XHR。要取消第一个 XHR,我需要跟踪 promise 对象(我正在使用 axios 来管理 XHR)。

我认为将运行中的 XHR 存储在 redux 存储中很有意义。像这样在 Redux 中存储承诺是不好的做法吗?它似乎不受欢迎 - Redux 真的应该只存储纯数据。

这在 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.

通常,像这样的任何异步行为都是通过 promise 或中间件(如 redux-thunk、redux-saga 或 redux-observable)在 Redux 存储外部处理的。有关这些方法之间的一些比较,请参阅最近的文章 Redux 4 Ways and 3 Common Approaches to Side-Effects in Redux