Created
January 4, 2020 08:13
-
-
Save chenxsan/1b97e606a96c72c3ad294c75d57d3b30 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
var buttonMachine = Machine({ | |
id: 'button', | |
initial: 'enabled', | |
context: { | |
list: [], | |
timer: 0 // 在 context 中保存计时 | |
}, | |
states: { | |
enabled: { | |
initial: 'idle', | |
states: { | |
idle: { | |
on: { | |
CLICK: { | |
target: 'loading' | |
} | |
} | |
}, | |
loading: { | |
entry: assign({ | |
// 进入 loading 状态时重置 timer | |
timer: 0 | |
}), | |
type: 'parallel', // 注意这个 parallel | |
// 表明 loading 下所有 states 是并行的 | |
states: { | |
fetching: { | |
// 一方面我们启动数据读取 | |
invoke: { | |
id: 'fetchData', | |
src: (context, event) => | |
window | |
.fetch('https://www.reddit.com/r/javascript.json') | |
.then(resp => resp.json()), | |
onDone: { | |
target: '#button.enabled.idle', | |
actions: assign({ | |
list: (context, event) => event.data | |
}) | |
}, | |
onError: { | |
target: '#button.enabled.idle' | |
} | |
} | |
}, | |
counting: { | |
// 另一方面我们启动读秒 | |
after: { | |
// 延时 1ms 后的状态切换 | |
1: { | |
target: 'counting', | |
actions: assign({ | |
timer: (context, event) => context.timer + 1 // 续 1ms | |
}) | |
} | |
} | |
} | |
} | |
} | |
} | |
}, | |
disabled: {} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment