简体   繁体   English

React Context API&HOC

[英]React Context API & HOC

I've been reading up on the new context API and have a question regarding using it alongside HOC to inject props instead of directly wrapping every child that needs access to some state with a Consumer. 我一直在阅读新的上下文API,并且有一个问题,就是将它与HOC一起使用来注入道具而不是直接包装需要访问某个州和消费者的每个孩子。

Isn't the above achievable without context? 没有上下文,上述是否可以实现? Isn't it possible to just house some state in a HOC and inject that into wrapped components that need access? 是不是可以在HOC中容纳一些状态并将其注入需要访问的包装组件中?

The documentation explains the use case where a lot of components need to access the common theme , and hence can be wrapped with an HOC. 该文档解释了许多组件需要访问公共主题的用例 ,因此可以用HOC包装。 without the context , you can make use of HOCs state to store the variable and pass on to the components wrapped with HOC but all of these components will have a different instance of the state and won't react to the theme change together. 如果没有context ,您可以使用HOCs状态来存储变量并传递给包含在HOC中的组件,但是所有这些组件都将具有不同的状态实例,并且不会同时对主题更改做出反应。

Context makes it possible to store the data centrally and all listeners/consumers will react to the change together. Context可以集中存储数据,所有监听器/消费者将共同对变化做出反应。

It is possible but each wrapped component will have it's own data passed from HOC. 这是可能的,但每个包装的组件将拥有从HOC传递的自己的数据。 While using context, this data is shared between components. 使用上下文时,此数据在组件之间共享。

So changing data in a context will make all Consumers re-render, while HOC will work only for the wrapped component. 因此,在上下文中更改数据将使所有Consumers重新呈现,而HOC仅适用于包装组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM