【问题标题】:How to use class service in React Native如何在 React Native 中使用类服务
【发布时间】:2022-01-10 15:54:22
【问题描述】:

我来自 Angular 世界,在那里我可以使用方法和属性来提供服务。然后我可以在另一个文件中导入这个类,将其注入构造函数并调用该类的成员。现在我正在使用 React Native 和 Expo 开发一个移动应用程序。我想知道我是否可以做同样的依赖注入。

这是我目前所拥有的:

// HttpService.ts

import....

export default class HttpService{
  private field = "";
  public method1 = () => {}
  public method2 = () => {}
  private otherMethod = () => {}
}

组件的用法:

// MakeApiCall.tsx
import HttpService from "./services/HttpService";
     
export...
// HttpService.method1 is not available.

我不想每次调用班级成员时都创建HttpService 的实例。

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    您可以导出该类的单例实例:

    // HttpService.ts
    import....
    
    class HttpService {
      private field = "";
      public method1 = () => {}
      public method2 = () => {}
      private otherMethod = () => {}
    }
    
    const singleton = new HttpService();
    export default singleton;
    
    // MakeApiCall.tsx
    import HttpService from "./services/HttpService";
         
    HttpService.method1();
    

    【讨论】:

      【解决方案2】:

      从 Angular 开始,数据和组件的交互方式发生了变化。与注入服务相比,React 更喜欢钩子形式的小型可组合函数。一开始它们可能看起来很复杂,但一旦你学会了它们就会很好地使用它们。

      简而言之,与其创建 HTTP 服务,不如使用经过测试的 fetch 框架为每个方法创建一个钩子。 Hooks 可以独立测试并且可以共享逻辑,如下所示:

      import useFetch from 'react-fetch-hook';
      
      export function useMethod1() {
        return useFetch('/api/data1');
      }
      
      export function useMethod2() {
        return useFetch('/api/data2');
      }
      
      // Usage
      
      import {useMethod1, useMethod2} from '../hooks/data';
      
      export function Display() {
      
        const { isLoading, data, error } = useMethod1();
      
        if (error) return <p>{{error}}</p>;
      
        if (isLoading) return <p>Loading...</p>;
      
        return <ul>{{data.map(d => (<li>{{d}}</li>))}}</ul>;
      
      }
      
      

      如果您打算使用服务,那么this article by LogRocket 可能有助于解决您正在使用的用例。

      【讨论】:

      • 谢谢。这行得通。
      猜你喜欢
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2022-07-01
      • 2016-12-06
      • 2016-03-25
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      相关资源
      最近更新 更多