与Redux有反应吗?那么“上下文”问题呢?

JavaScript

YOC40059608

2020-03-12

我通常将代码相关的内容发布在Stack上,但这更多是关于社区的一般思想的问题。

似乎有很多人主张将Redux与React结合使用来管理数据/状态,但是在阅读和学习两者的过程中,我遇到了一些看起来不太正确的事情。

Redux

在此页面底部:http : //redux.js.org/docs/basics/UsageWithReact.html(通过商店),建议使用React“上下文”的“魔术”。

一种选择是将其作为道具传递给每个容器组件。但是,这很麻烦,因为您甚至必须通过演示组件来进行存储,因为它们恰好在组件树的深处呈现了一个容器。

我们建议的选项是使用特殊的React Redux组件,该组件神奇地使商店可用于所有容器组件...

反应

在React Context页面(https://facebook.github.io/react/docs/context.html)上,它在顶部有一个警告:

上下文是一项先进的实验功能。该API可能会在将来的版本中更改。

然后在底部:

正如在编写清晰的代码时最好避免使用全局变量一样,在大多数情况下也应避免使用上下文。

不要使用上下文通过组件传递模型数据。显式地将数据线程穿过树很容易理解...

所以...

Redux建议使用React'Context'功能,而不是store通过'props' 传递给每个组件。而React建议相反。

Also, it seems that Dan Abramov (the creator of Redux) now works for Facebook (the creator of React), just to confuse me more.

  • Am I reading all this right..?
  • What is the general current consensus on this issue..?

第1262篇《与Redux有反应吗?那么“上下文”问题呢?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
飞羽宝儿 2020.03.12

我对其他人一无所知,但我更喜欢使用react-redux的connect decorator包装我的组件,以便仅将我需要的商店中的道具传递到我的组件中。从某种意义上说,这证明了使用上下文是合理的,因为没有使用它(而且我通常知道,我负责的任何代码都不会使用它)。

测试组件时,我将测试未包装的组件。因为react-redux仅通过了我在该组件上需要的道具,所以我现在确切地知道在编写测试时需要哪些道具。

我想要指出的是,我从没在代码中看到单词上下文,没有使用它,因此在某种程度上,它不会影响我!这并没有说明Facebook的“实验性”警告。如果上下文消失,在Redux更新之前,我将像其他所有人一样陷入困境。

蛋蛋蛋蛋 2020.03.12

Context is an advanced feature and is subject to change. In some cases its conveniences outweigh its downsides so some libraries like React Redux and React Router choose to rely on it despite the experimental nature.

The important part here is the word libraries. If context changes its behavior, we as library authors will need to adjust. However, as long as the library doesn’t ask you to directly use the context API, you as the user shouldn’t have to worry about changes to it.

React Redux uses context internally but it doesn’t expose this fact in the public API. So you should feel much safer using context via React Redux than directly because if it changes, the burden of updating the code will be on React Redux and not you.

Ultimately React Redux still supports always passing store as a prop so if you want to completely avoid context, you have that choice. However I would say this is impractical.

TLDR: Avoid using context directly unless you really know what you are doing. Using a library that happens to rely on context internally is relatively safe.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android