简体   繁体   English

React & RXJS 非标

[英]React & RXJS non standard

Online the implementations I see for RXJS with React are lackluster compared to what I'm used to with Angular.在网上,我看到的 RXJS 和 React 的实现与我习惯的 Angular 相比显得乏善可陈。

All implementation examples that I've seen have the subscribe in the same file as the declaration.我见过的所有实现示例都将订阅与声明放在同一个文件中。 (some have the next in that same file too) (有些在同一个文件中也有下一个)

I'd like for a second here to abstract away from the notion of store and do something a little out of the box.我想在这里抽出一点,从存储的概念中抽象出来,做一些开箱即用的事情。

Here's a pattern that I use alot in Angular that I'd like to be able to reproduce in React:这是我在 Angular 中经常使用的模式,我希望能够在 React 中重现:

One file contains a bunch of RXJS Subject declarations.一个文件包含一堆 RXJS 主题声明。

they are subscribed to in various components of the app.它们在应用程序的各个组件中被订阅。

and some other components or the same ones have the.next() on those Subjects.并且一些其他组件或相同的组件在这些主题上有 .next() 。

How would I do that in React?我将如何在 React 中做到这一点?

For simplicity's sake here's a three file layout:为简单起见,这里有一个三文件布局:

src
 ├app
 │  └components
 │     ├EmmitingComponent.tsx
 │     └SubscribingCompoent.tsx
 └services
    └observables.tsx

And let's imagine it has one observable declared in the observable.tsx and subcribed to in the SubscribingCompoent.tsx and hydrated on click in the EmmitingComponent.tsx .让我们想象一下,它在 observable.tsx 中声明了一个observable.tsx ,并在 SubscribingCompoent.tsx 中SubscribingCompoent.tsx并在EmmitingComponent.tsx中单击时水合。

This is a use case for which there are no React docs online to be found.这是一个在网上找不到 React 文档的用例。

Please refer to this answer .请参考这个答案 You can simply use the Async component and pass it your observables.您可以简单地使用Async组件并将其传递给您的 observables。 If you do want to have a similar service approach, you can provide and assign the context to an instance of your service class as well as define the observables on the service itself.如果您确实想要使用类似的服务方法,您可以提供上下文并将其分配给您的服务实例 class 以及在服务本身上定义可观察对象。

return (
    <Async select={[names$]}>
        {result => <div>{result}</div>}
    </Async>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM