基于前两篇文章的铺垫,这一篇文章就很轻松了。

不同框架下应用xstate

官网为 vuereact 都提供了对应版本的 xstate ,具体细节能够参看:

  • vue应用xstate
  • react应用xstate

angular 没有官网版本,具体应用能够参考 在Angular中应用xstate。

应用原理

不论应用哪个框架,思路都大同小异:在状态机启动之后,监听 state 的扭转,获取实时的 context (上下文),而后映射到页面中。

angular 中,xstate 被当作服务援用,状态机在启动之后,咱们通过 rxjs状态转变转化成 observable对象,通过订阅去获取实时的 context (上下文)。

// 启动状态机private machineSrv = interpret(covidMachine, { devTools: true }).start();// 将状态机的变动转变成 observablestate$: Observable<any> = from(this.machineSrv).pipe(  filter(state => state.changed));

总结:

  • 启动状态机
  • 监听状态机变动

组件联动

具体到某个组件想要应用状态机,则在组件绝对应的生命钩子中引入启动后的状态机,获取 context

// app.component.tsexport class AppComponent {  countryData: any[];  countryList: any[];  state: any = {};  constructor(private covidSrc: CovidService) {    // 订阅状态机服务,获取上下文,而后赋值    this.covidSrc.state$.subscribe((covidState: any) => {      this.state = covidState;      const { countryRef, listCountries } = covidState.context;      this.countryList = listCountries ? listCountries : [];      this.countryData = countryRef        ? this.processData(countryRef.state.context)        : [];    });  }  /** Helper */  processData(data: any) {    // 数据处理  }}

赋值之后,把值映射到 html 中即可。

<p style="text-align:center" *ngIf="state.context">    {{ state.matches("idle") ? "Select a country" : null }}</p><!-- 下拉框 --><app-select [data]="countryList" (selectChange)="selectCountry($event)"></app-select><!-- 数字卡片 --><app-number [data]="countryData"></app-number><!-- 条形图 --><app-bar [data]="countryData"></app-bar>

总结

咱们拿到状态机,个别有两个作用:

  • 拿到状态,用 state.match 匹配状态

    <!-- 如果状态机处于“idle”状态时的解决 -->{{ state.matches("idle") ? "Select a country" : null }}
  • 拿到上下文(context),获取页面中须要的数据

    this.state = covidState;const { countryRef, listCountries } = covidState.context;this.countryList = listCountries ? listCountries : [];

至此,一个基于xstae的新冠动静追踪网页就搭建实现了,具体的细节打击能够参考线上Demo。

往期回顾:

  • (一) 利用xstate追踪新冠动静 - 我的项目搭建
  • (二) 利用xstate追踪新冠动静 - 实现状态机