使用x状态app机时。如何将初始状态设置为变量?当从另一个文件发送布尔值时,我希望初始状态为全屏或菜单。我想从某个页面发送一个布尔值到应用程序机器,并根据该值更改初始状态。
{
id: "interactiveVideoMachine",
context: {
useFullscreenDefault: false,
},
user: {
id: "user",
initial: `${useFullscreen ? "fullscreen" : "menu"}`, // <--here
states: {
menu: {/*...*/},
fullscreen: {/*...*/},
},
on: {
SET_FULLSCREEN_DEFAULT: {
actions: "setFullscreenDefault",
},
},
},
};
{
actions: {
setFullscreenDefault,
},
};
const setFullscreenDefault: AssignAction<
InteractiveVideoContext,
InteractiveVideoEvent
> = actions.assign({
useFullscreenDefault: (ctx, event) => event.useFullscreenDefault,
});
let isFullscreenDefault: boolean;
const handleFullScreenDefault = () => {
console.log(isFullscreenDefault); //log here
if (interactiveVideoStateService) {
interactiveVideoStateService.send({
type: "SET_FULLSCREEN_DEFAULT",
isFullscreenDefault,
});
}
};
在设置初始值时,我通常使用机器工厂功能:
function createInteractiveVideoMachine({
useFullscreen,
}: {
useFullscreen: boolean;
}) {
return createMachine({
id: "interactiveVideoMachine",
states: {
user: {
id: "user",
initial: `${useFullscreen ? "fullscreen" : "menu"}`, // <--here
states: {
menu: {
/*...*/
},
fullscreen: {
/*...*/
},
},
},
},
});
}
然后像这样使用它:
let isFullscreenDefault: boolean;
const { state, send } = useMachine(createInteractiveVideoMachine({useFullscreen: isFullscreenDefault}));