并行状态节点 Parallel State Node

在状态图中,你可以将状态声明为 并行状态。 这意味着它的所有子状态将同时运行。 要了解更多信息,请参阅 中的部分。

API

通过设置 type: 'parallel' 在状态机和/或任何嵌套复合状态上指定并行状态节点。

例如,下面的状态机允许 uploaddownload 复合状态同时处于活动状态。 想象一下,这代表一个可以同时下载和上传文件的应用程序:

```js {3,5,21} const fileMachine = createMachine({ id: ‘file’, type: ‘parallel’, states: { upload: { initial: ‘idle’, states: { idle: { on: { INIT_UPLOAD: { target: ‘pending’ } } }, pending: { on: { UPLOAD_COMPLETE: { target: ‘success’ } } }, success: {} } }, download: { initial: ‘idle’, states: { idle: { on: { INIT_DOWNLOAD: { target: ‘pending’ } } }, pending: { on: { DOWNLOAD_COMPLETE: { target: ‘success’ } } }, success: {} } } } });

console.log(fileMachine.initialState.value); // => { // upload: ‘idle’, // download: ‘idle’ // }

  1. <iframe src="https://stately.ai/viz/embed/?gist=ef808b0400ececa786ec17e20d62c1e0"></iframe>
  2. 并行状态节点的状态值表示为一个对象。 此对象状态值可用于进一步转换到并行状态节点中的不同状态:
  3. ```js
  4. console.log(
  5. fileMachine.transition(
  6. {
  7. upload: 'pending',
  8. download: 'idle'
  9. },
  10. { type: 'UPLOAD_COMPLETE' }
  11. ).value
  12. );
  13. // => {
  14. // upload: 'success',
  15. // download: 'idle'
  16. // }

复合状态节点可以包含并行状态节点。 嵌套状态节点的配置相同:

  1. const lightMachine = createMachine({
  2. // 不是并行状态机
  3. id: 'light',
  4. initial: 'green',
  5. states: {
  6. green: {
  7. on: {
  8. TIMER: { target: 'yellow' }
  9. }
  10. },
  11. yellow: {
  12. on: {
  13. TIMER: { target: 'red' }
  14. }
  15. },
  16. // 嵌套并行状态机
  17. red: {
  18. type: 'parallel',
  19. states: {
  20. walkSign: {
  21. initial: 'solid',
  22. states: {
  23. solid: {
  24. on: {
  25. COUNTDOWN: { target: 'flashing' }
  26. }
  27. },
  28. flashing: {
  29. on: {
  30. STOP_COUNTDOWN: { target: 'solid' }
  31. }
  32. }
  33. }
  34. },
  35. pedestrian: {
  36. initial: 'walk',
  37. states: {
  38. walk: {
  39. on: {
  40. COUNTDOWN: { target: 'wait' }
  41. }
  42. },
  43. wait: {
  44. on: {
  45. STOP_COUNTDOWN: { target: 'stop' }
  46. }
  47. },
  48. stop: {
  49. type: 'final'
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. });
  57. console.log(lightMachine.transition('yellow', { type: 'TIMER' }).value);
  58. // {
  59. // red: {
  60. // walkSign: 'solid',
  61. // pedestrian: 'walk'
  62. // }
  63. // }