编程语言
首页 > 编程语言> > javascript – React Context vs React Redux,我应该何时使用每一个?

javascript – React Context vs React Redux,我应该何时使用每一个?

作者:互联网

React 16.3.0 was releasedContext API不再是实验性功能. Dan Abramov(Redux的创建者)就此发表了一篇很好的评论here,但是当Context仍然是一个实验性功能时,它是2年.

我的问题是,在您的观点/经验中何时应该使用React Context而不是React Redux,反之亦然?

解决方法:

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

正如马克埃里克森在他的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, middleware to add centralized
application logic, and other powerful capabilities that Redux
enables.

Redux功能更强大,提供了Context Api不提供的大量功能,正如As @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.

它直到Redux实际更新其实现以遵守最新的上下文API

最新的Context API可以用于您只需使用Redux在组件之间传递数据的应用程序,但是使用集中数据并使用redux-thunk或redux-saga在Action创建者中处理API请求的应用程序仍然需要redux.除此之外,redux还有其他库,如redux-persist,它允许您将存储数据保存在localStorage中,并在刷新时重新水化,这是上下文API仍然不支持的.

正如@dan_abramov在其博客You might not need 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.

有了这么多应用程序,很快就会说Redux将被新的Context API取代

标签:javascript,reactjs,redux,react-redux,react-context
来源: https://codeday.me/bug/20190917/1809676.html