React 16.3.0 was released和 Context API 不再是实验性功能。 Dan Abramov(Redux 的创建者)写了一个很好的评论 here关于这一点,但 Context 仍然是一个实验性功能已经 2 年了。
我的问题是,根据您的意见/经验,我应该在什么时候使用 React Context 而不是 React Redux,反之亦然?
最佳答案
由于 Context 不再是一项实验性功能,您可以直接在您的应用程序中使用 Context,它非常适合将数据传递到其设计用途的深度嵌套组件。
正如 Mark Erikson 在他的 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 thatRedux
enables.
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.
由 Redux 实际更新其实现以遵守最新的 Context API。
最新的 Context API 可用于您只需使用 Redux 在组件之间传递数据的应用程序,但是使用集中数据并使用 redux-thunk
在 Action 创建者中处理 API 请求的应用程序或redux-saga
仍然需要 Redux。除此之外,Redux 还有其他与之相关的库,例如 redux-persist
,它允许您在 localStorage 中保存/存储数据并在刷新时重新水化,这是 Context 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, ala 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 - React Context vs React Redux,我应该什么时候使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568073/