xstate에서 작업이 실행될 때

7177 단어 statechartsxstate
인기 있는statecharts 라이브러리에서 xstate과 함께 작업하는 동안actions 언제 어떻게 실행되는지 이해하지 못하는 함정에 빠졌습니다.

대부분의 경우 실제로 중요하지 않습니다. 할 때까지. 내가 "현명하게"사용하려고 할 때까지 transient transitions .

주어진 following statechart :

const machine = Machine(
  {
    initial: 'idle',
    context: {
      winning: 'heads',
      selected: 'tails'
    },
    states: {
      idle: {
        on: {
          SELECT: [
            { target: 'playing' }
          ]
        },
      },
      playing: {
        // It might seem that entry level action fires first.
        entry: ['flipCoin'],
        on: {
          '': [
            // And *after* that the guard is checked.
            // But this is not how it works.
            { target: 'score', cond: 'isScore' },
            { target: 'nope' }
          ]
        }
      },
      nope: {
        type: 'final'
      },
      score: {
        type: 'final'
      },
    }
  }, {
    guards: {
      isScore(context) {
        console.log('guard isScore');
        return context.selected === context.winning;
      },
    },
    actions: {
      flipCoin(context) {
        context.selected = 'heads';
        console.log('action flipCoin');
      }
    }
  }
);

entry action이 flipCoin라고 하면 state selected='heads'가 guard isScore가 반환되므로 true (4967914)로 끝납니다. ) .

그러나 이것은 일이 작동하는 방식이 아닙니다. final state에 따르면 :

Actions are not immediately triggered. Instead, the State object returned from machine.transition(...) will declaratively provide an array of .actions that an interpreter can then execute.



그래서 내 머리에 :

After event is sent to xstate, the next state of the statechart is determined based on current context before any actions are fired.




the documentation에 Clyde He의 사진

좋은 웹페이지 즐겨찾기