是否不鼓励使用 Context 进行组件之间的通信?

Is using Context for communication between components discouraged?

在阅读了有关 context (https://reactjs.org/docs/context.html) 的官方文档后,我觉得它的使用应该主要限于我们有一些变量的情况,我们可以考虑 "global" 我们必须发送到不同嵌套级别的许多组件(如当前主题、语言环境、当前经过身份验证的用户)。

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

我想使用Context来方便组件树中相距较远的组件之间的通信。许多用户为此使用了 Redux(虽然这不是它的主要目的),这并没有同样令人沮丧,即使当与 React 一起使用时(通过 react-redux 包)这种方法在内部由 Context 提供支持。

Context 与 redux + react-redux 相比有什么缺点(除非 Redux 有不同的更新状态的方式),这应该让我在描述的场景中不使用 Context 吗?文档说这使得组件重用更加困难。它是如何做到的,这个 con 不也与 redux + react-redux duo 相关吗?

你的问题我不是很清楚。但是考虑到你所说的反应文档的声明,

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

我从文档中看到的是caveat:您可能需要提升状态。

在您的项目中使用上下文 api 之前需要考虑一些事情,如果不这样做,您可能会失败。我想这是为了你能记住的语句"Apply it sparingly because it makes component reuse more difficult."。文档中概述了以下几点,您可以如何使用上下文 api 可以考虑为各种需要重用组件:

而且您可能会明显感觉到困难。否则,我可以看到,除了 redux 记录器之外,它可以使用我们可以用 redux 做的事情。

不气馁,可以用于不同层次嵌套的组件通信

Is there any disadvantage that Context has compared to redux + react-redux (barring the fact that Redux has a different way to update state) that should make me not use Context in the described scenario? The docs say it makes component reuse more difficult.

React context 调试起来不太方便,因为它目前无法使用 Redux devtools。有 an issue that can be watched, yet any possible solution can't cover interactions through context API that are performed with callback functions, e.g. ,同时可以跟踪调度的 Redux 操作。

文档没有解释为什么难以重用,'difficult' 是主观的。依赖于上下文的组件对组件层次结构中的相应 Provider 强加了隐藏的依赖性。它与它松散耦合,但如果没有预期的提供值,它可能会发生故障;如果没有 ProviderConsumer 仍使用 undefined 值呈现,如果不手动验证值,则无法更改此行为。