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

标签 reactjs redux react-context

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

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 提供支持。

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

最佳答案

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

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可以观看,但任何可能的解决方案都不能涵盖通过回调函数执行的上下文 API 的交互,例如this modal example ,同时可以跟踪分派(dispatch)的 Redux 操作。

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

关于reactjs - 是否不鼓励使用 Context 进行组件之间的通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623899/

相关文章:

javascript - 父级更新会导致上下文使用者重新安装?

css - 在 MUI v5 中更改抽屉的颜色

reactjs - 具有自定义根和基本组件的 React Router

reactjs - 错误: An immer producer returned a new value *and* modified its draft.返回一个新值*或*修改草稿

reactjs - 卸载后取消 Redux 操作

reactjs - 使用 Redux 两个 React 表单组件之间的通信

reactjs - 在 Next.js 中,如何使用 getServerSideProps 中的数据更新 React Context 状态?

javascript - 如何使用 React 的上下文功能将 HTML5 Canvas 上下文传递给 this.props.children?

reactjs - react 导航变量标签宽度

html - 空表格单元格的可访问性