[英]Using react hooks in conjunction with redux-saga (or any other middleware)
This question was already asked here before, however I didn't find yet any proper answer, just wonder if I missed anything or if indeed this is currently not possible.之前已经在这里问过这个问题,但是我还没有找到任何正确的答案,只是想知道我是否错过了任何东西,或者这确实是目前不可能的。
Specifically, there are 2 main differences between hooks & redux-saga (or any other middleware):具体来说,钩子和 redux-saga(或任何其他中间件)之间有两个主要区别:
So, is it possible to "bridge" somehow between these 2 approaches, or should I simply pick the most appropriate technique for each specific case?那么,是否有可能以某种方式在这两种方法之间“架起”桥梁,或者我应该为每种特定情况选择最合适的技术?
They are different tools to solve different problems.它们是解决不同问题的不同工具。 Hooks work internally to a functional component's state and lifecycle.挂钩在功能组件的 state 和生命周期内部工作。 Redux works internally to an entire react app's state and lifecycle. Redux 在内部工作于整个反应应用程序的 state 和生命周期。 Sagas help wrangle asynchronous effects like external data fetches. Sagas 有助于解决异步效果,例如外部数据获取。
Generally speaking you want to limit the scope of variables and logic as much as possible.一般来说,您希望尽可能限制变量和逻辑的 scope。 If a specific piece of "state" is only relevant to a single component, then keep it in component state.如果特定的“状态”仅与单个组件相关,则将其保存在组件 state 中。 But if several components or the application itself needs it, then store it in app state.但如果有多个组件或应用程序本身需要它,则将其存储在应用程序 state 中。 Same applies for asynchronous calls.同样适用于异步调用。 If a single external call is used by only one component, keep it there, but if multiple components can make the same external async calls, then let the sagas handle them.如果只有一个组件使用单个外部调用,请将其保留在那里,但如果多个组件可以进行相同的外部异步调用,则让 sagas 处理它们。
You are free to use as much, or as little, as is necessary of either in each component to solve your problem.您可以根据需要在每个组件中随意使用尽可能多或尽可能少的内容来解决您的问题。
useReducer
hook you can trigger code on action dispatch, with useEffect
you can trigger code on mount/update/unmount etc.钩子更通用,例如使用useReducer
钩子可以在动作分派时触发代码,使用useEffect
可以在挂载/更新/卸载等上触发代码。App
component, it is not some random component , it is the right place to put the logic to.所以基本上如果你有一些全局应用程序逻辑并在你的App
组件中为它放置一个钩子,它不是一些随机组件,它是放置逻辑的正确位置。 I've also recently found a simple library https://www.npmjs.com/package/use-saga-reducer that introduces sagas to React's useReducer
.我最近还发现了一个简单的库https://www.npmjs.com/package/use-saga-reducer将 sagas 引入 React 的useReducer
。 (I'm still not sure it is a good idea - just because you can doesn't mean you should, for me hooks async functions are usually enough, but it is at least interesting) (我仍然不确定这是一个好主意 - 仅仅因为你可以并不意味着你应该,对我来说,钩子异步函数通常就足够了,但它至少很有趣)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.