What happens if you send an event that doesn't exist in React Xstate?

妖精的绣舞 提交于 2021-01-29 21:20:34

问题


Take this finite-state machine:

{
  initial: "foo",
  states: {
    foo: {
      on: { BAR: "bar" }
    },
    bar: {
      on: { FOO: "foo" }
    }
  }
}

And in my component, I do this:

import { useMachine } from "@xstate/react";

export default function() {
  const [current, send] = useMachine(machine);

  useEffect(() => {
    send("BAR");
  }, []);

  return (
    <>
      Hello World  
    </>
  );
}

This is perfectly valid code and the machine will switch to the "bar" state. Now, what happens if I do this?

useEffect(() => {
  send("QUX");
}, []);

The QUX event is not defined in the machine.


回答1:


In this scenario a state machine interpreter is supposed to disregard the unplanned event. This is how state machine works. No transition evaluation will take place if event can't be find.

As per State Machine definition

A state machine is a finite set of states that can transition to each other deterministically due to events.

Planned events result in planned transitions (if guards passed).

Take into account that if you are in foo state, but the event "QUX" is defined upper in states hierarchy, the interpreter would find it and evaluate transition defined there.

In a hierarchical machine, transitions are prioritized by how deep they are in the tree; deeper transitions are more specific and thus have higher priority. This works similar to how DOM events work: if you click a button, the click event handler directly on the button is more specific than a click event handler on the window.

More on this case can be found in here, in chapter 'Transitions' of Xstate docs.




回答2:


If strict mode is not turned on (it is not on by default), the "StateNode" will try to transition to the appropriate candidate state based on the event, find none, and do nothing.

Here is a link to the code that determines whether to error or not, and a small snippet:

if (this.strict) {
  if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {
    throw new Error(
      `Machine '${this.id}' does not accept event '${_event.name}'`
    );
  }
}


来源:https://stackoverflow.com/questions/58904591/what-happens-if-you-send-an-event-that-doesnt-exist-in-react-xstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!