跳到主要内容

认识

2023年05月28日
柏拉文
越努力,越幸运

语法


基础语法

import { createMachine, interpret } from "xstate";

const toggleMachine = createMachine({
id: "toggle",
initial: "close",
states: {
close: {
on: {
CLICK: "open",
},
},
open: {
on: {
CLICK: "close",
},
},
},
});

const toggleService = interpret(toggleMachine).onTransition((state) => {
console.log(state.value);
});
toggleService.start();
toggleService.send({ type: "CLICK" });
toggleService.send({ type: "CLICK" });

assign 语法

import { createMachine, interpret,assign } from "./xstate";

const toggleMachine = createMachine({
id: "number",
initial: 'ready',
context:{
text:0
},
states: {
ready: {
on: {
"CHANGE":{
actions:[
assign({text:(context,event)=>event.value})
]
}
},
},
},
});

const toggleService = interpret(toggleMachine).onTransition((state) => {
console.log(state.context);
});
toggleService.start();
toggleService.send({ type: "CHANGE",value:1 });

react 应用语法

import React from "react";
import ReactDOM from "react-dom";
import { createMachine, assign } from "xstate";
import { useMachine } from "@xstate/react";

const numberMachine = createMachine({
id: "number",
initial: "ready",
context: {
text: 0,
},
states: {
ready: {
on: {
CHANGE: {
actions: [assign({ text: (context, event) => event.value })],
},
},
},
},
});

function Number() {
const [state, send] = useMachine(numberMachine);
const {
context: { text },
} = state;
const handleAdd = () => {
send({ type: "CHANGE", value: text + 1 });
};
return (
<div>
<h3>{text}</h3>
<button onClick={handleAdd}>增加</button>
</div>
);
}

function App() {
return (
<div>
<h3>React 状态 XState</h3>
<Number />
</div>
);
}

ReactDOM.render(<App />, document.getElementById("root"));