Skip to content

Output

Output 是 actor 在“完成任务”时产出的最终结果

什么时候才有Output?

  • 状态机进入 final state
  • Promise actor resolve
  • 子 actor 完成并返回结果
ts
snapshot.status === 'done'

定义output

在machine中声明output

ts
const machine = createMachine({
  context: {
    count: 0,
  },
  output: ({ context }) => ({
    total: context.count,
  }),
})

Final State 中声明 Output

详情见States>output

读取output

ts
actor.subscribe(snapshot => {
  if (snapshot.status === 'done') {
    console.log(snapshot.output.total)
  }
})

Promise Actor 的 Output

ts
import { fromPromise, createActor } from 'xstate'

const promiseLogic = fromPromise(async () => {
  const res = await fetch('/api/data')
  return res.json() as { message: string }
})

const actor = createActor(promiseLogic)

actor.subscribe(snapshot => {
  if (snapshot.status === 'done') {
    console.log(snapshot.output.message)
  }
})

actor.start()