Xstate 中存储的动作创建者消息在哪里?
Where is the action creator message stored in Xstate?
import { Machine, assign } from 'xstate';
// example: property assigner
// ...
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'
}),
// ...
"Count changed" 存储在哪里?在上下文中?
是的,正确!
Here是codesandbox中的一个demo来演示,分解图:
我围绕分配操作创建了一个机器,它可以更好地演示将要发生的事情:
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>
</>
}
渲染的初始组件将是:
并且在单击 "Transition" 按钮时,事件 SWITCH_OFF
将被发送到机器,导致动作触发,上下文中的计数递增,并分配消息。
导致组件呈现以下内容:
import { Machine, assign } from 'xstate';
// example: property assigner
// ...
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'
}),
// ...
"Count changed" 存储在哪里?在上下文中?
是的,正确!
Here是codesandbox中的一个demo来演示,分解图:
我围绕分配操作创建了一个机器,它可以更好地演示将要发生的事情:
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>
</>
}
渲染的初始组件将是:
并且在单击 "Transition" 按钮时,事件 SWITCH_OFF
将被发送到机器,导致动作触发,上下文中的计数递增,并分配消息。
导致组件呈现以下内容: