为什么使用 React Context 比仅仅传递 props 对象更好?

Fra*_*cis 3 reactjs react-context

我一直在阅读有关在 React 中使用 Context 的优点的文章,但我并不相信。我想知道是否有什么我错过了。

Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。

在主组件中创建 props 对象并在下属之间传递它有什么麻烦?就像是:

// do this once at top level (I'm assuming [foo, foo_set] and [bar, bar_set] are state variables):
const props = {foo, foo_set, bar, bar_set, thisAndThat, theOther, whatever, etcAndEtc}

// including one component
<MyComponent1 {...props } />

// including another
<MyComponent2 {...props } />
Run Code Online (Sandbox Code Playgroud)

(也许对该对象使用另一个名称而不是 props 更好,因为组件可以具有其他属性。无论如何。)

然后在 MyComponent1 中你可以访问所有你想要的 props,也可以不访问它们。任何一个:

...
const MyComponent1 = (props) => {
...
// here we can use any props we need, props.bar, props.bar_set, props.theOther for example
const localVar = props.bar * 2;
props.bar_set(localVar);
// this changes the value of bar throughout the app
...
}
Run Code Online (Sandbox Code Playgroud)

在我看来,上述的优点是您可以将 props 对象传递给其他子子组件,而不必担心是否缺少任何内容。或者:

...
const MyComponent1 = ({bar, bar_set, theOther }) => {
...
// here we can use bar, bar_set, theOther in the same example
const localVar = bar * 2;
bar_set(localVar);
...
}
Run Code Online (Sandbox Code Playgroud)

此选项的优点是语法更短。

所以我的观点是为什么不直接使用标准 JavaScript 语法呢?当有很多新概念可以用来做各种其他事情时,为什么还要引入新概念呢?

Nic*_*wer 9

考虑大多数应用程序的一个相当常见的情况:您有身份验证信息(例如,当前用户)、路由库(例如,react-router)和主题对象(使用什么颜色)。这些是分散在整个应用程序中的组件所需要的。

您想要在组件树顶端的某个位置渲染一个按钮。它将显示用户的头像,因此需要身份验证数据。点击时会进行导航,因此需要路由库中的导航功能。并且它需要根据主题来设计自己的风格。

这当然可以通过 props 来完成,但是为了让按钮获取 props,其上方链中的每个组件也必须获取并转发这些 props。这可能是许多深层组件,例如页面组件 -> 节组件 -> 表 -> 行 -> 小部件 -> 按钮,并且大多数组件本身不需要这些信息,因此它们只是按顺序获取 props转发它。

您可以轻松想象整个应用程序需要 3 条以上数据的情况。

有什么麻烦的

大多数人认为这种“螺旋钻探”很麻烦,但我们假设您不这么认为。您仍然遇到性能不佳的问题。如果每个组件都必须接收应用程序可能需要的全套“全局”值,那么任何时候发生任何变化,整个应用程序都必须重新渲染。像react.memo这样的优化实际上变得毫无用处。如果你只传递你需要的道具,你会得到更好的表现。