我來自 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每次呼叫班級成員時都新建一個實體。
uj5u.com熱心網友回復:
您可以匯出該類的單例實體:
// 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();
uj5u.com熱心網友回復:
來自 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>;
}
如果您打算使用服務,那么LogRocket 的這篇文章可能有助于解決您正在使用的用例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/407772.html
標籤:
上一篇:將道具傳遞給組件時出現型別錯誤
下一篇:在圖庫中使用虛擬滾動
