在 React 中使用 XState 检查当前机器状态的问题
我试图从反应组件(state.value)中的函数内部检查机器状态,但它永远不会改变当前状态,它总是打印初始状态,但如果我在组件中放置 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
im trying to check the Machine state from inside a function in a react component (state.value), but its never change the current state, it always prints the initial state, but if i put a onClick event in the component and call console.log(state.value), it works... Im doing something wrong?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是由于陈旧的关闭造成的。您始终在循环中读取
state
的封闭值。相反,您可以从
service.getSnapshot()
读取:This is likely due to a stale closure. You are always reading the closed-in value of
state
in the loop.Instead, you can read from
service.getSnapshot()
: