[英]unable to restore state machine with persisted state using xstate and react
[英]Problem to check the current machine state using XState in React
我試圖從反應組件(state.value)中的 function 內部檢查機器 state,但它從不更改當前的 state,它始終打印初始 state,但如果我在組件中放置 onClick 事件並調用控制台。 log(state.value),有效……我做錯了什么?
const [state, send] = useMachine(knightMachine);
const loop = () => {
console.log(state.value);
setTimeout(loop, 10);
}
/// Always print the initial state.
<div
onClick={() => {
console.log(state.value);
}}
></div>
/// It Prints the right value
這可能是由於陳舊的關閉。 你總是在循環中讀取state
的閉包值。
相反,您可以從service.getSnapshot()
讀取:
const [state, send, service] = useMachine(knightMachine);
// ...
console.log(service.getSnapshot().value); // up-to-date value
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.