Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何管理React&;中的依赖关系;下一代?_Reactjs_Dependency Injection_Next.js - Fatal编程技术网

Reactjs 如何管理React&;中的依赖关系;下一代?

Reactjs 如何管理React&;中的依赖关系;下一代?,reactjs,dependency-injection,next.js,Reactjs,Dependency Injection,Next.js,如何在React中管理依赖项注入 我来自一个角度的世界,所有服务都是单例类(即,整个应用程序中只有一个类实例)。在我的React应用程序中,我尝试将一些“服务”(即执行HTTP请求或身份验证的东西)抽象到它们自己的类中。我猜这是一个反模式的反应 例如,我有一个HttpService作为: class HttpService { public readonly axios = axios; constructor() { console.log('NEW HTTP SERVICE

如何在React中管理依赖项注入

我来自一个角度的世界,所有服务都是单例类(即,整个应用程序中只有一个类实例)。在我的React应用程序中,我尝试将一些“服务”(即执行HTTP请求或身份验证的东西)抽象到它们自己的类中。我猜这是一个反模式的反应

例如,我有一个HttpService作为:

class HttpService {
  public readonly axios = axios;

  constructor() {
    console.log('NEW HTTP SERVICE');
    this.registerInterceptors();
  }

  public registerInterceptors(): void {
    axios.interceptors.request.use(CacheRequestInterceptor);
    axios.interceptors.request.use(AuthInterceptor);
    axios.interceptors.response.use(CacheResponseInterceptor);
  }

  public get<T>(url: string, config: AxiosRequestConfig = {}): Observable<T> {
    return from(this.axios.get(url, config)).pipe(
      map((res) => {
        return res.data;
      })
    );
  }
// ... and so on
所以很明显,这不是我想要的工作方式(我只想要一个HTTP服务实例)

在React中实现这一点的最佳方式是什么?它会使用高阶组件吗


提前谢谢

您可以在React/Next项目中创建服务模块。如果只需要类的一个实例,则需要使用一些全局存储,在其中可以存储对类实例的引用

您可以使用或状态管理库,如

这个日志并不能证明您实现的单例模式不起作用。您正在开发模式(
next dev
)下运行应用程序,其中应用程序会根据每个请求编译。您需要在生产模式下运行它(
next build
next start
)来测试它

nextjs-ui: NEW HTTP SERVICE
nextjs-ui: event - build page: /login
nextjs-ui: wait  - compiling...
nextjs-ui: event - compiled successfully
nextjs-ui: NEW HTTP SERVICE
nextjs-ui: event - build page: /admin
nextjs-ui: wait  - compiling...
nextjs-ui: event - compiled successfully
nextjs-ui: NEW HTTP SERVICE

您可以在React/Next项目中创建服务模块。如果只需要类的一个实例,则需要使用一些全局存储,在其中可以存储对类实例的引用

您可以使用或状态管理库,如

这个日志并不能证明您实现的单例模式不起作用。您正在开发模式(
next dev
)下运行应用程序,其中应用程序会根据每个请求编译。您需要在生产模式下运行它(
next build
next start
)来测试它

nextjs-ui: NEW HTTP SERVICE
nextjs-ui: event - build page: /login
nextjs-ui: wait  - compiling...
nextjs-ui: event - compiled successfully
nextjs-ui: NEW HTTP SERVICE
nextjs-ui: event - build page: /admin
nextjs-ui: wait  - compiling...
nextjs-ui: event - compiled successfully
nextjs-ui: NEW HTTP SERVICE