是,对的!
下面是代码沙箱中的一个演示来演示它,以及它的细分:
我围绕 assign 操作创建了一台机器,可以更好地演示会发生什么:
const testMachine = Machine(
{
id: "testMachine",
initial: "lightOn",
context: {
count: 0,
message: ""
},
states: {
lightOn: {
on: {
SWITCH_OFF: {
target: "lightOff",
actions: assign({
// increment the current count by the event value
count: (context, event) => context.count + event.value,
// assign static value to the message (no function needed)
message: "Count changed"
})
}
}
},
lightOff: {
on: {
SWITCH_ON: "lightOn"
}
}
}
}
);
在 react 中使用机器看起来像这样:
import * as React from "react";
import { useMachine } from "@xstate/react";
import { testMachine } from "./machines";
export default function Test() {
const [current, send] = useMachine(testMachine);
return <>
<div>Message:{current.context.message}</div>
<div>Count:{current.context.count}</div>
<button onClick={() => send('SWITCH_OFF', { value: 1 })}>Transition</button>
</>
}
渲染的初始组件将是:

单击“转换”按钮后,事件SWITCH_OFF
将被发送到机器,从而触发动作,并在上下文中增加计数,并分配消息。
导致组件呈现以下内容:
