createMachine
APIconst doorMachine = createMachine({
// Machine identifier
id: "door",
// Initial state
initial: "关着",
// State definitions
states: {
关着: {
on: {
// 也可以用字串描述
开门: "开了"
}
},
开了: {
on: {
// 可用物件描述
关门: { target: "关着" }
}
}
}
});
使用 interpret
API 来建立 service,并且 透过 onTransition
监听 转移,每当有转移时就可以执行一个 callback ,参数是 state ,我们这里先尝试用 console
每当转移时就印出 state。
// Interpret the machine, and add a listener for whenever a transition occurs.
const service = interpret(doorMachine).onTransition((state) => {
console.log(`State is ${state.value}`);
});
3-1. 启动 service
// Start the service
service.start();
3-2. 操作 service,派发事件
console.warn("send Event 开门");
service.send("开门"); // 用 string 表示 event
console.warn("send Event 关门");
service.send("关门");
console.warn("send Event 关门 again");
// 关着状态 + 关门事件,不转移状态
service.send({ type: "关门" }); // 也可以用 object 表示 event
console.warn("send Event 开门 again");
service.send({ type: "开门" });
3-3. 结束 service (当你不再需要使用这个状态机时)
// Stop the service when you are no longer using it.
service.stop();
假设此时我们在底下继续执行这个 instance
// Stop the service when you are no longer using it.
service.stop();
console.warn("send Event 开门 again");
service.send({ type: "开门" });
它不会继续运作,我们会看到 XState 在主控台用 warning 提示,此时可以再透过 start
方法,重启 service
// Restart the machine
service
.start()
.onTransition((state) =>
console.error("重启了的 Machine State 是 ", state.value)
);
service.send({ type: "关门" });
今天学习了 如何建立 state Machine 的 instance / service ,包含启动、派发事件、关闭、重启、监听转移事件等
之前提到下面的几个特色,除了第一点,其他也会在後续继续带大家一起认识
https://xstate.js.org/docs/guides/interpretation.html#interpreting-machines
>>: Day 19 民生公共物联网资料应用竞赛,产品设计讨论过程分享
boxing: 封装可以让原始型态的资料暂时转成物件,这样他才可以使用属性或方法。 遇到使用字面值(...
前言 这个演讲蛮general的,也适合任何leader来看看。如果你觉得team里面的人都不太爱...
《30天带你上完 Google Data Analytics Certificate 课程》系列将...
开一个 docker-compose.yml 填入 version: "3.5"...
今天是第一天,我先简单的介绍一下网站服务器是如何运作的。还有如果在遭遇大量流量时,可能会有哪些状况。...