React Context - Context.Consumer 与 Class.contextType [英] React Context - Context.Consumer vs Class.contextType

查看:25
本文介绍了React Context - Context.Consumer 与 Class.contextType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在了解一些新引入的 React.Context API,但我注意到它在跨示例的消耗方面存在一些不一致之处.有些使用原始的 Context.Consumer HOC 方法,而有些(包括 React Docs)使用静态的 Class.contextType 方法.有什么区别?为什么不一致?

I am learning about the somewhat newly introduced React.Context API, but I've noticed some inconsistencies on it's consumption across examples. Some use the original Context.Consumer HOC method, while some (including the React Docs) use the static Class.contextType method. What's the difference and why the inconsistency?

推荐答案

原来 static Class.contextType新引入 React v16.6.0,正如 Context.Consumer 方法所证明的类组件有问题.此外,使用两者之间似乎有一个主要区别,那就是静态 Class.Context 只允许您订阅单个上下文.

Turns out that the static Class.contextType was newly introduced on React v16.6.0, as the Context.Consumer method proved problematic on class components. Also, there does seem to be one major difference between using both, and it's that the static Class.Context only allows you to subscribe to a single context.

好消息是,它们似乎都能可靠地侦听 Context 更改,这意味着如果您只有一个 Context API,那么两者都足够了.

The good news is that both of them seem to reliably listen of Context changes which means if you only have a single Context API, then both are good enough.

这篇关于React Context - Context.Consumer 与 Class.contextType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆