本文介绍了何时使用原生 React.useReducer Hook 以及它与 Redux 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,从 React 16.8 开始可以使用 Hook.从他们的文档中可以看出,Hooks 是功能组件中状态的替代者.基本的钩子有:useStateuseEffectuseContext,但也有一些额外的钩子,其中之一是useReducercode>,看起来它使用与 Redux 相同的 action-dispatch 架构.

So, Hooks are available from React 16.8. From their documentation, Hooks come as a replacer of state in functional components. The basic hooks are: useState, useEffect, useContext, but there are also some additional hooks, one of them being useReducer, and it looks like it uses the same action-dispatch architecture as Redux does.

问题是它是否会因为相似而取代 Redux?

The questions would be if it comes as a replacement of Redux because of the resemblance ?

它是否更适合特定项目?

Does it suits particular projects better ?

它适合哪里?

推荐答案

Redux 是一个以特定方式鼓励数据流的库.

Redux is a library that encourages data flow in a specific manner.

react-redux 另一方面实现了 React 友好的方法,并提供了很多中间件和包装器,这样库使用者就不必自己设置整个过程.

react-redux on the other hand implements the React friendly approach and provides a lot middlewares and wrappers so that the library consumers do not have to set up the entire process on their own.

虽然 useReducer 是 Redux 工作方式的一部分,但它并不是 Redux 的全部.为了让您在组件的深处使用 dispatch 和 state,您仍然必须将 useContextuseReducer 结合使用,这就像重新发明轮子一样.

While useReducer is a part of how Redux works, it isn't Redux in its entirety. In order for you to use dispatch and state deep down in your components you would still have to use useContext and useReducer in a combination which would be like re-inventing the wheel.

除此之外,useReducer 只是为您提供了一个 dispatch 方法,您可以使用该方法将普通的旧对象作为操作进行分派.目前还没有办法将 middlewares 添加到诸如 thunksaga 等等.

On top of that useReducer just gives you a dispatch method which you can use to dispatch plain old objects as actions. There is no way yet to add middlewares to these such as thunk, saga and many more.

您还可以使用 useReducer 在您的应用程序中使用多个 reducer,但是如何将它们组合以形成单个存储仍然必须由开发人员管理.

You also can have multiple reducers in your application using useReducer but then the way to combine these to form a single store still have to be managed by the developer.

另外 React docs 声明 useReducer 是当状态逻辑复杂时,可以替代 useState

Also React docs state that useReducer is an alternative to useState when state logic is complex

useReducer 通常比 useState 更可取涉及多个子值或下一个状态时的状态逻辑取决于前一个.useReducer 还可以让你优化触发深度更新的组件的性能,因为您可以向下传递调度而不是回调.

useContextuseReducer 之类的钩子的作用是消除小型应用程序对 Redux 的依赖.

What hooks like useContext, useReducer do is that they eliminate the dependency on Redux for small apps.

这篇关于何时使用原生 React.useReducer Hook 以及它与 Redux 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:28