反应依赖注入还是类似? [英] React dependency injection or similar?

查看:73
本文介绍了反应依赖注入还是类似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular.js中,可以使用依赖注入。我做了一些浏览,无法找到它的实现。 React有没有类似的东西?

In Angular.js it is possible to use dependency injection. I did some browsing and was not able to find an implementation of it. Does React have something similar to that?

推荐答案

反应有IoC,但没有任何一个像Angular这样的DI容器的概念。也就是说,您不必拥有知道如何创建对象和传递依赖关系的容器,而是在实例化时将道具传递给组件(如< MyComponent items = {this.state .items} /> )。

React has IoC, but not any concept of a DI container like Angular. That is, instead of having a container that knows how to create objects and passing in dependencies, you pass them explicitly by passing props to the component when you instantiate it (like <MyComponent items={this.state.items} />).

传递依赖关系作为道具不是很常见的反应世界。道具主要用于将数据传递到组件而不是服务/商店。但是没有什么可以阻止你将服务/商店甚至组件作为道具(而且肯定没有错)。

Passing dependencies as props isn't very common the React world though. Props are mostly used to pass data to components and not services/stores. But there's nothing stopping you from passing services/stores or even components as props (and certainly nothing wrong with it).

React有一个 context 它是一个整个组件树的共享对象。因此,顶级组件可以说,其子树的上下文具有包含诸如UserStore,MessageStore等的对象。组件层次结构中进一步向下的组件可以表示它希望在其上下文中访问UserStore。通过说,该组件可以访问UserStore,而不必将其从顶部组件显式传递到底部,并且请求它的组件不知道如何创建/传递给它。

React has the concept of a context which is a shared object for a whole tree of components. So the top level component can say that the context for its subtree has an object containing something like a UserStore, a MessageStore, etc. A component further down in the component hierarchy can then say that it wants access to the UserStore in its context. By saying that, the UserStore is accessible to that component without having to explicitly pass it down from the top component to the bottom, and the component requesting it doesn't know how it was created/passed to it.

它具有DI容器的优点,您可以在其中拥有可以进一步传递的对象创建的中心位置。以下是上下文的一个很好的介绍: https://www.tildedave .com / 2014/11/15 / introduction-to-contexts-in-react-js.html

It has the benefit of a DI container where you have a central place for object creation which can be passed in further down. Here's a good intro to contexts: https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html

上下文仍然是React的一个未记录的功能,这意味着它的API可以在React的任何未来版本中更改,因此您可能需要稀疏地使用它,直到成为文件。

Contexts are still an undocumented feature of React, which means that its API can change in any coming versions of React, so you might want to use it sparsely until it becomes documented.

这篇关于反应依赖注入还是类似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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