如果你发送一个在 React Xstate 中不存在的事件会发生什么?
What happens if you send an event that doesn't exist in React Xstate?
以这个有限状态机为例:
{
initial: "foo",
states: {
foo: {
on: { BAR: "bar" }
},
bar: {
on: { FOO: "foo" }
}
}
}
在我的组件中,我这样做:
import { useMachine } from "@xstate/react";
export default function() {
const [current, send] = useMachine(machine);
useEffect(() => {
send("BAR");
}, []);
return (
<>
Hello World
</>
);
}
这是完全有效的代码,机器将切换到 "bar" 状态。现在,如果我这样做会怎样?
useEffect(() => {
send("QUX");
}, []);
QUX
事件未在计算机中定义。
如果没有开启严格模式(默认不开启),"StateNode"会尝试根据事件过渡到合适的候选状态,找到none,然后执行没什么。
Here is a link到判断是否报错的代码,以及一小段:
if (this.strict) {
if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {
throw new Error(
`Machine '${this.id}' does not accept event '${_event.name}'`
);
}
}
在这种情况下,状态机解释器应该忽略计划外事件。这就是状态机的工作原理。如果找不到事件,则不会进行转换评估。
根据状态机definition
A state machine is a finite set of states that can transition to each other deterministically due to events.
计划的事件导致计划的转换(如果守卫通过)。
考虑到如果您处于 foo
状态, 但是 事件 "QUX"
定义在状态层次结构的上层,解释器会发现它并评估那里定义的过渡。
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.
有关此案例的更多信息,请参见 Xstate 文档的 here 章 'Transitions'。
以这个有限状态机为例:
{
initial: "foo",
states: {
foo: {
on: { BAR: "bar" }
},
bar: {
on: { FOO: "foo" }
}
}
}
在我的组件中,我这样做:
import { useMachine } from "@xstate/react";
export default function() {
const [current, send] = useMachine(machine);
useEffect(() => {
send("BAR");
}, []);
return (
<>
Hello World
</>
);
}
这是完全有效的代码,机器将切换到 "bar" 状态。现在,如果我这样做会怎样?
useEffect(() => {
send("QUX");
}, []);
QUX
事件未在计算机中定义。
如果没有开启严格模式(默认不开启),"StateNode"会尝试根据事件过渡到合适的候选状态,找到none,然后执行没什么。
Here is a link到判断是否报错的代码,以及一小段:
if (this.strict) {
if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {
throw new Error(
`Machine '${this.id}' does not accept event '${_event.name}'`
);
}
}
在这种情况下,状态机解释器应该忽略计划外事件。这就是状态机的工作原理。如果找不到事件,则不会进行转换评估。
根据状态机definition
A state machine is a finite set of states that can transition to each other deterministically due to events.
计划的事件导致计划的转换(如果守卫通过)。
考虑到如果您处于 foo
状态, 但是 事件 "QUX"
定义在状态层次结构的上层,解释器会发现它并评估那里定义的过渡。
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.
有关此案例的更多信息,请参见 Xstate 文档的 here 章 'Transitions'。