首页 > 解决方案 > 如何在 redux 中存储自动完成结果并做出反应

问题描述

我试图弄清楚如何最好地使用 react、redux 和自动完成组件。目前,我正在使用react-select。我遇到的问题是何时何地进行 API 调用以检索自动完成结果。

我尝试了两种方法来解决这个问题:

  1. 从组件内部或通过从包装组件的容器传入的回调进行 API 调用。这对我来说很好。我想单元测试会因此变得不那么整洁。

  2. 在击键时引发 redux 操作。在动作创建者中进行 API 调用。通过使用 redux-thunk 中间件,promise 被解析,并在搜索结果中引发了一个新操作,因为它是有效负载并存储在 store 的某些部分中。自动完成组件一直在监听这个列表并呈现结果列表。我部分地使用了react-select,但是输入组件的状态在随后的击键中被清除了。

我正在寻找有关这两种方法的优缺点的指导,以及是否有最佳实践可供采用。

谢谢。

标签: reactjsautocompletereduxredux-thunkreact-select

解决方案


In case, anyone lands here looking for an update.

After working with react for months now and having more experience, I can mention here the path I took.

While it's possible to store the autocomplete results in a redux store, there is little advantage to this. I did implement this as an experiment. Since these results are ephemeral for the user, it's perfectly reasonable to store inside the components state. This is this final approach I took.

As an aside, if the autocomplete is used multiple times on a page, there is a case to potentially cache results against search queries to reduce requests on the server and improve client-side perf. I decided to use redux here to share the data across the multiple instances of the autocomplete in my situation.

I also changed the autocomplete library from react-select to downshift to gain more control over the implementation of my autocomplete.

YMMY as always.


推荐阅读