按照指南,我来到了 redux 应用程序的各种中间件。
Redux Thunk , Redux Promise , Redux Promise Middleware , Redux Observable , Redux Saga , Redux Pack
我们选择哪种中间件只是一个偏好问题。但我并不是要求选择约定。
我想知道它们之间是否存在任何差异,例如性能、浏览器支持、用例等,或者我遗漏的任何其他内容。我对这些进行了艰苦的研究,但找不到任何文章。
这样我就可以考虑为我的应用程序选择一个中间件。如果我知道使用不同中间件的特定用例,那么选择中间件对我来说也很好。
或者,所有中间件都只是约定,我可以为任何类型的 redux 应用程序(小型或大型)选择其中的任何一个?
请您参考如下方法:
To be able to choose one of these libraries我们必须考虑我们是在构建小型应用程序还是大型应用程序。还可以考虑可用性、代码标准和 JavaScript 知识。它们都很相似。
redux-thunk
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. It incorporates the methods dispatch and getState as parameters.
redux-saga
redux-saga is a library that aims to make application side effects (i.e. asynchronous like data fetching and impure procedures such as accessing the browser cache) in a manageable and efficient way to execute. It's simple to test as it uses the ES6 feature called generators, making the flow easy to read as synchronous code.
redux-observable
redux-observable is a middleware for redux that is inspired by redux-thunk. It allows developers to dispatch a function that returns an Observable, Promise or iterable of action(s). When the observable emits an action, or the promise resolves an action, or the iterable gives an action out, that action is then dispatched as usual.
其他人直接来自他们的 github 源:
redux-promise
The middleware returns a promise to the caller so that it can wait for the operation to finish before continuing. This is especially useful for server-side rendering.
redux-promise-middleware
Redux promise middleware enables robust handling of async action creators in Redux: it accepts a promise and dispatches pending, fulfilled and rejected actions. The middleware can also be combined with Redux Thunk to chain action creators.
redux-pack
redux-pack is a library that introduces promise-based middleware that allows async actions based on the lifecycle of a promise to be declarative.
Async actions in redux are often done using redux-thunk or other middlewares. The problem with this approach is that it makes it too easy to use dispatch sequentially, and dispatch multiple "actions" as the result of the same interaction/event, where they probably should have just been a single action dispatch.
This can be problematic because we are treating several dispatches as all part of a single transaction, but in reality, each dispatch causes a separate rerender of the entire component tree, where we not only pay a huge performance penalty, but also risk the redux store being in an inconsistent state.
redux-pack helps prevent us from making these mistakes, as it doesn't give us the power of a dispatch function, but allows us to do all of the things we were doing before.