本文介绍了React 中的 Angular 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Angular,正在尝试学习 React (Native).我们如何在 React 中实现 Angular 的服务"概念?

例如,我想执行以下操作:

For example, I would like to do the following:

  1. 从外部 API 获取数据为 json
  2. 对数据做一些事情,例如修改每一项
  3. 使修改后的数据可供应用的多个组件使用

这在 Angular 中使用服务极其简单方便,并将该服务注入到任何需要访问数据的组件中.

This is extremely easy and convenient in Angular using a Service, and injecting that Service into any Components that need access to the data.

这是如何在 React 中实现的?

推荐答案

在 vanilla React 中,服务的直接对应物是组件.与 Angular 不同,React 组件不必存在于 DOM 中.类似于 Angular 中的服务和组件/指令,React 中的关注点分离可以通过 容器和展示组件.容器组件可以处理业务逻辑,而表现逻辑则归于表现组件.

A direct counterpart to a service in vanilla React is a component. As opposed to Angular, React components don't have to exist in DOM. Similarly to services and components/directives in Angular, the separation of concerns in React can be provided with container and presentational components. Container component can handle business logic, while presentation logic goes to presentational component.

由于 React 偏爱函数式方法,重用的代码不一定要进入一个类,而是可以用函数组合来表达.

Since React favours functional approach, reused code doesn't necessarily goes to a class and can be expressed with functional composition instead.

React 中的组件层次结构提供了依赖注入模式.它可以通过几种常见的方式实现,以使数据(如服务实例)可用于整个应用程序或其中的一部分,例如通过深度传递的 props、上下文 API、第三方状态管理(Redux、MobX).

Dependency injection pattern is provided with component hierarchy in React. It can be implemented in several common ways to make data (like service instance) available for entire application or a part of it, e.g. via deeply passed props, context API, third-party state management (Redux, MobX).

const fetchData = () => fetch(...).then(res => res.json());
const processData = data => ...;
const fetchProcessedData = () => fetchData().then(processData);

class ContainerComponent extends React.Component {
  state = {};

  componentDidMount() {
    fetchProcessedData().then(data => {
      this.setState({ data });
    });
  }

  render() {
    return {this.state.data && <PresentationalComponent data={data}/>};
  }
}

PresentationalComponent 通过 data 属性注入依赖.

PresentationalComponent is injected with a dependency through data prop.

同样的例子可以用 Angular 组件实现,但这会导致不需要的 DOM 元素.

The same example would be possible to implement with Angular components but this would result in unwanted DOM elements.

当 Redux 用于状态管理时,诸如获取(副作用)之类的事情由服务于此目的的扩展程序处理,例如redux-thunk、redux-saga 等,同步处理由 reducer 处理.

When Redux is used for state management, things like fetching (side effects) are handled by extensions that serve this purpose, e.g. redux-thunk, redux-saga, etc. While synchronous processing is handled by reducers.

这篇关于React 中的 Angular 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:24