React 的状态机抽象
React Automata 一个用于 React 的状态机抽象,提供了声明式的状态管理和自动生成测试。快速入门 安装 react 和 react-test-renderer 是同级依赖项。 sh yarn add react-automata 使用 js // App.js import React from 'react' import { Action, withStateMachine } from 'react-automata' const statechart = { initial: 'a', states: { a: { on: { NEXT: 'b', }, onEntry: 'sayHello', }, b: { on: { NEXT: 'a', }, onEntry: 'sayCiao', }, }, } class App extends React.Component { handleClick = () = { this.props.transition('NEXT') } render() { return ( ) } } export default withStateMachine(statechart)(App) js // App.spec.js import { testStateMachine } from 'react-automata' import App from './App' test('it works', () = { testStateMachine(App) }) js // App.spec.js.snap exports[it works: a 1] = ; exports[it works: b 1] = ; API withStateMachine(statechart[, options])(Component) withStateMachine 高阶组件接受一个 xstate 配置对象或 xstate 机器、一些选项和一个组件。它返回一个带有特殊属性、动作和活动方法的新组件,以及额外的生命周期钩子。初始机器状态和初始数据可以通过 initialMachineState 和 initialData 属性传递给所得组件。选项 | 选项 | 类型 | 描述 | | ------ | ---- | ----------- | | channel | 字符串 | 设置状态的上下文的键。 | | devTools | 布尔值 | 将状态机连接到 Redux DevTools 扩展。 | 属性 transition(event[, updater]) 更改状态机状态的方法。它接受一个可选的更新器函数,该函数接收上一个数据并返回数据更改。更新器也可以是一个对象,它会被合并到当前数据中。 js handleClick = () = { this.props.transition('FETCH') } machineState 状态机的当前状态。不建议使用此值,因为它将组件和状态机耦合在一起。 js {this.props.machineState === 'idle' ? 'Fetch' : 'Retry'} 动作和活动方法 所有与动作和活动名称匹配的组件方法,在相关的转换发生时会被触发。js handleClick = () = { this.props.transition('FETCH') } machineState 状态机的当前状态。不建议使用此值,因为它将组件和状态机耦合在一起。 js {this.props.machineState === 'idle' ? 'Fetch' : 'Retry'} Action and Activity methods All the component's methods whose names match the names of actions and activities, are fired when the related transition occurs.
暂无开放 Issues,或尚未同步最近议题。