Javascript React Context 与 React Redux,我应该什么时候使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49568073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:24:26  来源:igfitidea点击:

React Context vs React Redux, when should I use each one?

javascriptreactjsreduxreact-reduxreact-context

提问by Alfrex92

React 16.3.0 was releasedand the ContextAPI is not an experimental feature anymore. Dan Abramov (the creator of Redux) wrote a good comment hereabout this, but it was 2 years when Context was still an Experimental feature.

React 16.3.0 已发布ContextAPI 不再是实验性功能。Dan Abramov(Redux 的创建者)在这里写了一篇很好的评论,但是 Context 仍然是一个实验性功能已经 2 年了。

My question is, in your opinion/experience when should I use React Contextover React Reduxand vice versa?

我的问题是,根据您的意见/经验,我什么时候应该使用React Context 而不是React Redux,反之亦然?

回答by Shubham Khatri

As Contextis no longer an experimental feature and you can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for.

由于Context不再是一个实验性功能,您可以直接在您的应用程序中使用 Context 并且非常适合将数据传递给它设计的深层嵌套组件。

As Mark erikson has written in his blog:

正如马克·埃里克森在他的博客中所写:

If you're only using Redux to avoid passing down props, context could replace Redux - but then you probably didn't need Redux in the first place.

Context also doesn't give you anything like the Redux DevTools, the ability to trace your state updates, middlewareto add centralized application logic, and other powerful capabilities that Reduxenables.

如果您只是使用 Redux 来避免传递 props,则 context 可以替换 Redux - 但是您可能一开始就不需要 Redux。

Context 也没有为您提供诸如Redux DevTools跟踪状态更新的能力、middleware添加集中式应用程序逻辑以及其他强大的功能Redux

Reduxis much more powerful and provides a large number of features that the Context Apidoesn't provide, also as As @danAbramovmentioned

Redux更强大,并提供了大量Context Api不提供的功能,正如@danAbramov 所提到的

React Redux uses context internally but it doesn't expose this fact in the public API. So you should feel much safer using context via React Redux than directly because if it changes, the burden of updating the code will be on React Redux and not you.

React Redux 在内部使用上下文,但它没有在公共 API 中公开这个事实。所以你应该觉得通过 React Redux 使用上下文比直接使用上下文要安全得多,因为如果它发生变化,更新代码的负担将落在 React Redux 而不是你身上。

Its upto Redux to actually update its implementation to adhere with the latest context API

由 Redux 来实际更新其实现以符合最新的上下文 API

The latest Context API can be used for Applications where you would simply be using Redux to pass data between component, however application which use centralised data and handle API request in Action creators using redux-thunkor redux-sagastill would need redux. Apart from this redux has other libraries associated like redux-persistwhich allow you to save store data in localStorage and rehydrate on refresh which is what context API still doesn't support.

最新的 Context API 可用于应用程序,您只需使用 Redux 在组件之间传递数据,但是使用集中数据并在 Action creators 中处理 API 请求的应用程序使用redux-thunkredux-saga仍然需要 redux。除了这个 redux 之外,还有其他相关的库,例如redux-persist允许您将存储数据保存在 localStorage 中并在刷新时补水,而上下文 API 仍然不支持。

As @dan_abramov mentioned in his blog You might not need Redux, that redux has useful application like

正如@dan_abramov 在他的博客中提到的你可能不需要 Redux,redux 有一些有用的应用程序,比如

  • Persist state to a local storage and then boot up from it, out of the box.
  • Pre-fill state on the server, send it to the client in HTML, and boot up from it, out of the box.
  • Serialize user actions and attach them, together with a state snapshot, to automated bug reports, so that the product developers
    can replay them to reproduce the errors.
  • Pass action objects over the network to implement collaborative environments without dramatic changes to how the code is written.
  • Maintain an undo history or implement optimistic mutations without dramatic changes to how the code is written.
  • Travel between the state history in development, and re-evaluate the current state from the action history when the code changes, a la TDD.
  • Provide full inspection and control capabilities to the development tooling so that product developers can build custom tools for their
    apps.
  • Provide alternative UIs while reusing most of the business logic.
  • 将状态持久化到本地存储,然后从它启动,开箱即用。
  • 在服务器上预填充状态,将它以 HTML 格式发送到客户端,然后从它启动,开箱即用。
  • 序列化用户操作并将它们与状态快照一起附加到自动错误报告中,以便产品开发人员
    可以重放它们以重现错误。
  • 通过网络传递动作对象以实现协作环境,而无需对代码的编写方式进行重大更改。
  • 维护撤消历史或实现乐观突变,而不会对代码的编写方式进行重大更改。
  • 在开发中的状态历史之间穿梭,并在代码更改时从动作历史中重新评估当前状态,即 TDD。
  • 为开发工具提供完整的检查和控制功能,以便产品开发人员可以为其
    应用程序构建自定义工具。
  • 在重用大部分业务逻辑的同时提供替代 UI。

With these many application its far too soon to say that Redux will be replaced by the new Context API

有了这么多应用程序,现在说 Redux 将被新的 Context API 取代还为时过早

回答by GG.

If you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the ContextAPI. It is exactly intended for this use case.

如果您使用 Redux 只是为了避免将 props 传递给深层嵌套的组件,那么您可以用ContextAPI替换 Redux 。它完全适用于这个用例。

On the other hand, if you are using Redux for everything else(having a predictable state container, handling your application's logic outside of your components, centralizing your application's state, using Redux DevToolsto track when, where, why, and how your application's state changed, or using plugins such as Redux Form, Redux Saga, Redux Undo, Redux Persist, Redux Logger, etc…), then there is absolutely no reason for you to abandon Redux. The ContextAPI doesn't provide any of this.

另一方面,如果您将 Redux 用于其他所有事情(具有可预测的状态容器,在组件之外处理应用程序的逻辑,集中应用程序的状态,使用Redux DevTools跟踪应用程序的状态何时、何地、为什么以及如何更改,或者使用Redux FormRedux SagaRedux UndoRedux PersistRedux Logger等插件……),那么你绝对没有理由放弃 Redux。该ContextAPI不提供任何这一点。

And I personally believe that the Redux DevTools extensionis an amazing, underestimated debugging tool, which justifies by itself to keep using Redux.

而且我个人认为Redux DevTools 扩展是一个了不起的、被低估的调试工具,它本身就有理由继续使用 Redux。

Some references:

一些参考:

回答by vijayst

I prefer using redux with redux-thunk for making API calls (also using Axios) and dispatching the response to reducers. It is clean and easy to understand.

我更喜欢使用 redux 和 redux-thunk 进行 API 调用(也使用 Axios)并将响应分派给 reducer。它干净且易于理解。

Context API is very specific to the react-redux part on how React components are connected to the store. For this, react-redux is good. But if you want to, since Context is officially supported, you could use the Context API instead of react-redux.

Context API 非常特定于关于 React 组件如何连接到 store 的 react-redux 部分。为此,react-redux 很好。但是如果你愿意,因为官方支持 Context,你可以使用 Context API 而不是 react-redux。

So, the question should be Context API vs react-redux, and not Context API vs redux. Also, the question is slightly opinionated. Since, I am familiar with react-redux and use it in all projects, I will continue to use it. (There is no incentive for me to change).

所以,问题应该是 Context API vs react-redux,而不是 Context API vs redux。另外,这个问题有点自以为是。因为,我熟悉 react-redux 并在所有项目中使用它,我将继续使用它。(我没有动力去改变)。

But if you are learning redux just today, and you have not used it anywhere, it is worth giving Context API a shot and replace react-redux with your custom Context API code. Maybe, it is much cleaner that way.

但是如果你刚刚在学习 redux,而且你还没有在任何地方使用过它,那么值得给 Context API 一个机会,并用你的自定义 Context API 代码替换 react-redux。也许,这样会干净得多。

Personally, it is a question of familiarity. There is no clear reason to choose one over the other because they are equivalent. And internally, react-redux uses Context anyways.

就个人而言,这是一个熟悉程度的问题。没有明确的理由选择一个而不是另一个,因为它们是等效的。在内部,react-redux 无论如何都使用 Context。

回答by Sebastien Lorber

The only reasons to use Redux for me are:

对我来说使用 Redux 的唯一原因是:

  • You want a global state object (for various reasons, like debuggability, persistence...)
  • Your app is or will be big, and should scale to many developers: in such case you probably need a level of indirection (ie an event system): you fire events (in the past) and then people you don't know in your organisation can actually listen to them
  • 您需要一个全局状态对象(出于各种原因,例如可调试性、持久性...)
  • 您的应用程序很大或将会很大,并且应该扩展到许多开发人员:在这种情况下,您可能需要一个间接级别(即事件系统):您触发事件(过去),然后触发您不认识的人组织实际上可以听取他们的意见

You probably don't need the level of indirection for your whole app, so it's fine to mix styles and use local state/context and Redux both at the same time.

您可能不需要整个应用程序的间接级别,因此可以混合样式并同时使用本地状态/上下文和 Redux。

回答by Micha? Rejman

  • If you need to use middleware for various purposes.For example logging actions, error reporting, dispatching other requests depending on the server's response, etc.
  • When data coming from multiple endpoints influence single component/view.
  • When you want to have greater control over actions in your applications.Redux enables tracking actions and data change, it greatly simplifies debugging.
  • If you don't want server response to directly change the state of your application.Redux adds a layer, where you can decide how, when and if this data should be applied. The observer pattern. Instead of creating multiple publishers and subscribers across the whole app, you just connect components to Redux store.
  • 如果您需要将中间件用于各种目的。例如记录操作、错误报告、根据服务器的响应调度其他请求等。
  • 当来自多个端点的数据影响单个组件/视图时。
  • 当您想要更好地控制应用程序中的操作时。Redux 支持跟踪操作和数据更改,它极大地简化了调试。
  • 如果您不希望服务器响应直接更改应用程序的状态。Redux 添加了一个层,您可以在其中决定如何、何时以及是否应用这些数据。观察者模式。您只需将组件连接到 Redux 商店,而不是在整个应用程序中创建多个发布者和订阅者。

From: When to use Redux?

来自:什么时候使用 Redux?