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

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

问题描述

在 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?

推荐答案

React 有 IoC,但没有像 Angular 这样的 DI 容器的任何概念.也就是说,不是让容器知道如何创建对象和传递依赖项,而是通过在实例化组件时将 props 传递给组件来显式传递它们(例如 <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} />).

不过,将依赖项作为 props 传递在 React 世界中并不常见.props 主要用于将数据传递给组件而不是服务/商店.但是没有什么可以阻止您将服务/商店甚至组件作为道具传递(当然也没有什么问题).

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天全站免登陆